Serverless & Event-Driven Compute
"Serverless computing offers the potential to program the cloud in an autoscaling, pay-as-you-go manner." — Hellerstein et al., Serverless Computing: One Step Forward, Two Steps Back, CIDR 2019 (arXiv:1812.03651, abstract)
Summary: Serverless means you hand the servers, the scaling and the idle capacity to a provider and pay per request and per millisecond; the price is a hard execution model: short, stateless, at-least-once, limited, and billed by usage. Focus: FaaS vs serverless containers vs managed services, the AWS Lambda execution model (invocation types, event source mappings, Init and Invoke phases, cold starts, SnapStart, provisioned and reserved concurrency, limits), Cloud Run, Azure Functions, Cloudflare Workers isolates, Vercel and Fly Machines, event sources, partial batch responses, DLQs and destinations, idempotency, connection pooling, Step Functions and Durable Functions, cost per request and GB-second, VPC and observability gotchas, security, lock-in, and event-driven design. Learning goal: For one workload, decide whether functions, serverless containers or plain containers fit, size concurrency, batch and timeout with numbers, write a handler that survives duplicate and partial delivery, and predict the bill and the failure modes before deploying.
This chapter sits at the end of the Observability & Operations group: it needs Containers & Kubernetes (what you are giving up managing), Scaling Strategies (autoscaling and stateless design) and Observability (you cannot SSH into a function). It links to API Idempotency and Idempotent Consumers & the Inbox Pattern for the retry story, to Dead-Letter Queue and Durable Workflows & Jobs for failure and orchestration, and to CDNs for edge functions. Broker mechanics stay in the messaging section; this page owns the system-level decision and the numbers.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in five tables | Everything in one minute |
| What "serverless" promises and costs | Why it exists |
| Papers and product history | Where it comes from |
| FaaS vs serverless containers vs managed services | Definitions |
| Sync, async and poll-based invocation | Invocation types |
| Init, Invoke, freeze, reuse | Execution environment |
| Cold starts, SnapStart, provisioned concurrency | Cold starts |
| Reserved concurrency, limits, throttling | Concurrency |
| SQS, Kinesis, S3, EventBridge, SNS, cron | Event sources |
| Batch size, batch window, ReportBatchItemFailures | Batches and partial failure |
| DLQ, destinations, retries | Retries and DLQs |
| Idempotent handlers | Idempotency |
| State, connection pooling, RDS Proxy | Stateless by force |
| Step Functions, Durable Functions, choreography | Orchestration |
| Cloud Run, Azure, Workers, Vercel, Fly | Other platforms |
| Edge functions | Edge |
| Price per request and per GB-second | Cost model |
| VPC, payload, observability, testing | Gotchas |
| Roles, secrets, event injection | Security |
| Knative, OpenFaaS, SST, CDK | Portability |
| Fan-out, ordering, backpressure | Event-driven design |
| Exact limits and error names | Mechanics |
| Code | Go, Laravel |
| Classic failures | Solving the classic problems |
| Which compute for which workload | Choosing |
| Monolith to distributed system | In architecture |
| Numbers and commands | Lab |
| Beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The three families of "serverless".
| Family | You ship | Unit of scaling | Scale to zero | Typical products |
|---|---|---|---|---|
| FaaS (function as a service) | A function and its dependencies | One execution environment per concurrent request (Lambda) | Yes | AWS Lambda, Azure Functions, Cloud Run functions, Cloudflare Workers, Vercel Functions, Netlify Functions |
| Serverless containers | A container image that listens on a port | An instance that serves many concurrent requests | Yes (configurable) | Google Cloud Run, Knative Serving, Azure Container Apps, AWS Fargate (not scale-to-zero by itself) |
| Managed services ("serverless" data and glue) | Configuration | Hidden | Mostly (billed per use) | Amazon SQS, SNS, EventBridge, DynamoDB, S3, Step Functions |
Lambda invocation styles.
| Style | Who waits | Retries | Typical sources |
|---|---|---|---|
Synchronous (RequestResponse) | The caller gets the result or the error | The caller must retry | API Gateway, ALB, function URL, SDK Invoke |
Asynchronous (Event) | Nobody; Lambda queues the event and returns 202 | Lambda retries twice by default; DLQ or destination for the failures | S3, SNS, EventBridge, SDK with Event |
| Poll-based (event source mapping) | Lambda pollers read and invoke the function synchronously with a batch | Depends on the source: SQS message returns after the visibility timeout, streams retry the batch | SQS, Kinesis, DynamoDB Streams, MSK and self-managed Kafka, Amazon MQ |
Numbers worth remembering (Lambda, from the AWS quotas page read for this chapter).
| Number | Meaning |
|---|---|
| 1,800 s | Function timeout: 30 minutes (older documentation and many tutorials say 900 s, 15 minutes) |
| 128 to 10,240 MB | Memory; CPU is proportional; 1,769 MB is one vCPU |
| 6 MB / 1 MB | Request and response payload for synchronous / asynchronous invocation |
| 1,000 | Default account concurrency per Region (soft limit) |
| 1,000 per 10 s | Per-function scale-out rate: new execution environments |
| 10 s | Init phase limit for on-demand functions (not with SnapStart or provisioned concurrency) |
| 512 to 10,240 MB | /tmp size |
| 5 layers, 250 MB unzipped | Layers and unzipped package size; container images up to 10 GB |
The five rules the rest of the page unpacks.
| Rule | Why |
|---|---|
| Assume every event arrives twice | Event source mappings and asynchronous invokes are at least once |
| Keep nothing important in the function | Environments are created, frozen and destroyed at the provider's will |
| Put a queue between a spike and anything fragile | Concurrency limits and a queue turn a burst into a steady stream |
| Cap concurrency downstream of the function | Lambda scales faster than your database |
| Do the arithmetic before you choose | Cost is requests times duration times memory, not "cheap" |
The picture is the lifecycle of one execution environment. Cold start cost is the left box; everything about reuse, /tmp and connection caching happens between the boxes.
Why it exists
Running a server means paying for it while it is idle, patching it, sizing it for the peak and running enough of them to survive a failure. For a workload that is idle most of the day, or arrives in bursts, or is a glue step between two managed services, almost all of that effort and money is waste. The Berkeley view of serverless puts it this way: "Serverless cloud computing handles virtually all the system administration operations needed to make it easier for programmers to use the cloud." (Jonas et al., 2019). The same papers are frank about the cost: Hellerstein et al. argue that first-generation FaaS is a "bad fit" for data-centric and distributed computing.
| What you get | What you pay |
|---|---|
| No servers to patch or size | A fixed execution model: time, memory, payload and concurrency limits |
| Scale to zero: no idle bill | Cold starts: the first request after idle pays Init |
| Fast scale-out without a capacity plan | Scale-out can overwhelm databases and third-party APIs |
| Pay per request and per millisecond | Above a steady utilisation threshold it costs more than an instance |
| Built-in integration with queues, streams, schedules | Lock-in to the provider's event shapes and IAM |
| Isolation per invocation | No local state; every dependency is a network call |
The analogy we reuse: a taxi versus a car you own. A taxi costs nothing while you sleep and comes in minutes, and it is wonderful for the odd trip. If you drive eight hours every day, owning is cheaper, and a taxi never lets you leave your tools in the boot. A function is the taxi; a container on a reserved instance is the car; Cloud Run sits between (a car sharing scheme that parks itself).
Three common misunderstandings, up front
- "Serverless means there are no servers." There are servers; you do not manage them. The consequences you inherit are the limits (time, memory, payload) and the lifecycle (cold start, freeze, recycle).
- "Serverless is always cheaper." It is cheaper for idle and spiky load and more expensive for steady high utilisation. See the cost model.
- "It scales infinitely, so my system does." The function scales; your database, your payment API and your account concurrency limit do not. Scaling a stage without protecting the next one moves the outage downstream.
Where it comes from
AWS launched Lambda in 2014 with the event-driven model: code runs in response to events from S3, DynamoDB and later API Gateway. Google (App Engine, then Cloud Functions, now Cloud Run functions), Microsoft (Azure Functions) and Cloudflare (Workers, 2017, isolate-based) followed. In parallel the container world produced Knative (Serving and Eventing on Kubernetes) and OpenFaaS, so the model can run on your own cluster. Dates in this paragraph are from general knowledge, not from a page fetched for this chapter.
Two papers frame the debate:
- Jonas et al., "Cloud Programming Simplified: A Berkeley View on Serverless Computing" (UC Berkeley EECS-2019-3). It argues that serverless is the evolution of cloud programming "that parallels the transition from assembly language to high-level programming languages" and predicts that it "will grow to dominate the future of cloud computing". It lists obstacles: state, communication between functions, predictable performance.
- Hellerstein et al., "Serverless Computing: One Step Forward, Two Steps Back" (CIDR 2019). A critique: functions have limited lifetimes, no addressable network between them, no data locality, so data moves to the code instead of the code to the data. The "one step forward" is autoscaling and pay-as-you-go; the "two steps back" are the constraints on distributed and data-centric computing.
Both are read here through their abstracts (saved under the sources folder; the full PDFs were not extracted). Platform behaviour in this chapter comes from the vendor documentation fetched on the day of writing; limits change, so check the quotas page before you design near one.
The concept catalogue
Definitions: FaaS, serverless containers, managed services Must-know
In plain words: "Serverless" is a billing and operations promise, not a technology: you do not manage capacity and you pay for use. Functions are one way to get it; serverless containers are another.
Common misunderstanding: "Serverless equals Lambda." Google Cloud Run's documentation describes itself as "a fully managed application platform for running your code, function, or container" and scales to zero when idle. Knative Serving brings the same model to Kubernetes. A queue or a database can be serverless too (Amazon SQS and DynamoDB are billed per request).
Definition: A workload is serverless to the degree that (1) you provision no servers, (2) capacity follows load including down to zero, (3) you pay for what you use, not what you reserve, and (4) availability and patching are the provider's job.
request arrives -> no instance running
-> platform starts an instance (cold start)
-> instance serves the request (and maybe more, on Cloud Run)
-> instance idles
-> platform removes it (scale to zero)Real scenario: an image-resize function triggered by S3 uploads; a nightly report on a schedule; a webhook receiver for a SaaS that sends ten events a day; a Cloud Run service for an internal admin tool used during office hours.
| Question | FaaS (Lambda) | Serverless container (Cloud Run) | Always-on container |
|---|---|---|---|
| Concurrent requests per instance | One (default) | Many (default 80 per vCPU through the CLI, up to 1,000) | Many |
| Scale to zero | Yes | Yes unless minimum instances set | No |
| Packaging | Zip or image with a handler | Any container listening on a port | Any container |
| Max request time | 30 minutes (Lambda quotas page) | Configurable request timeout | Unbounded |
| Billing granularity | Per request plus GB-second | CPU and memory per 100 ms (Cloud Run documentation) | Per instance hour |
Fix / how to use it: decide at the workload level: event glue and spiky APIs to functions, HTTP services with steady-ish traffic to serverless containers, steady heavy services to containers.
Invocation types Must-know
In plain words: There are three ways a function runs: someone calls it and waits, someone drops an event in a mailbox and leaves, or Lambda itself reads a queue or stream and calls your function with a batch.
Common misunderstanding: "Lambda retries failed invocations." Only for some invocation types. A synchronous caller gets the error and must retry; asynchronous events are retried by Lambda; for a poll-based source the retry behaviour belongs to the source (SQS visibility timeout, stream shard blocking).
Definition: The Lambda Invoke API takes InvocationType: RequestResponse is synchronous, Event is asynchronous (the CLI shows StatusCode: 202). An event source mapping is a Lambda resource whose pollers read from a stream or queue and invoke the function synchronously with a batch of records.
sync caller -> Lambda -> function -> result -> caller (caller waits, caller retries)
async caller -> Lambda queue -> 202 to caller
queue -> function (retry x2, then DLQ or destination)
poll Lambda poller -> SQS/Kinesis -> batch -> function -> delete or report failuresReal scenario: API Gateway or a function URL is synchronous; S3 object-created and SNS are asynchronous; SQS, Kinesis and DynamoDB Streams use event source mappings.
| Property | Synchronous | Asynchronous | Event source mapping |
|---|---|---|---|
| Payload limit | 6 MB request and response | 1 MB | Batch size and 6 MB invoke payload |
| Retry owner | Caller | Lambda: 2 more attempts, 1 and 2 minute waits; throttling retried up to 6 hours | The source (SQS visibility timeout; stream retries) |
| Failure capture | Error in response | DLQ (SQS or SNS standard) or on-failure destination | SQS redrive DLQ; stream on-failure destination |
| Delivery semantics | Exactly what the caller does | At least once | At least once |
| Ordering | Not applicable | Not guaranteed | Per shard (streams), per message group (FIFO) |
Fix / how to use it: pick by who should wait. If the user is waiting, synchronous; if not, put a queue in front so that you control retries, DLQs and concurrency (see Event sources).
The execution environment and its lifecycle Must-know
In plain words: Your function runs inside a small sandbox that Lambda creates, uses for many invocations, freezes while idle and eventually throws away. Code outside the handler runs once per sandbox.
Common misunderstanding: "Each invocation gets a fresh process." Not necessarily: a warm environment is reused, so globals, open connections and files in /tmp can survive. That is an optimisation you may use and a hazard if you leak one user's data into the next.
Definition: The AWS documentation lists the phases: Init (start extensions, bootstrap the runtime, run the function's static code), Restore (SnapStart only), Invoke, and Shutdown. The Init phase for on-demand functions is limited to 10 seconds; if it does not finish, Lambda retries it at the first invocation with the configured timeout. The Invoke phase is limited by the function timeout, and the duration includes extensions. The environment is frozen when the runtime and all extensions have signalled completion and there is no pending event.
t0 request 1 -> no environment -> Init (1.2 s) -> Invoke (80 ms) cold start
t1 request 2 -> environment idle, frozen -> Invoke (75 ms) warm start
t2 request 3 and 4 at once -> env A busy, so env B: Init+Invoke (cold)
t3 long idle -> Shutdown, environment destroyedReal scenario: a Go function builds its AWS SDK client and parses configuration in package-level initialisation; the first request pays about 100 ms of Init, later ones pay none. A PHP function loads the framework kernel once per environment.
| Behaviour | Guaranteed? |
|---|---|
| Code outside the handler runs once per new environment | Yes |
| The same environment serves many sequential invocations | No guarantee; common under steady traffic |
/tmp survives between invocations | Only in a warm environment; never rely on it |
| Two concurrent requests share an environment | No; each concurrent request needs its own (Lambda default) |
| Background work continues after the handler returns | It is frozen; do not rely on it |
| Time between invocations is billed | No |
Fix / how to use it: build clients, pools and parsed config at Init; keep per-request state in locals; use a keep-alive for persistent connections because Lambda purges idle ones (the Go handler documentation says so); treat /tmp as a cache.
Cold starts, SnapStart and provisioned concurrency Must-know
In plain words: A cold start is the extra delay when Lambda has to build a new sandbox before running your code. Warm starts reuse one and skip that delay.
Common misunderstanding: "Cold starts make serverless unusable." For steady traffic they affect a small share of requests: Bref's documentation says cold starts represent about 0.2% of requests on applications with regular traffic, and that its PHP runtime adds roughly 250 ms on average. They matter for strict latency budgets and for low-traffic functions that scale to zero between requests. Bref states plainly that if you cannot tolerate any response above 300 ms, Lambda is not the right fit.
Definition: Cold start time is Init (extension init, runtime init, function init) plus the platform's sandbox creation and code download. Three mitigations exist on Lambda: smaller packages and lighter init; SnapStart, which initialises when you publish a version, snapshots memory and disk state of the initialised environment and resumes new environments from the snapshot; and provisioned concurrency, which keeps a set number of environments initialised.
on demand: request -> create sandbox -> download code -> Init -> Invoke
SnapStart: publish version -> Init -> snapshot
request -> restore snapshot -> (after-restore hooks) -> Invoke
provisioned: configure N -> N environments Init ahead of time
request -> Invoke (double-digit milliseconds per the AWS documentation)Real scenario: a latency-sensitive JVM API with several seconds of framework init uses SnapStart; a payment-adjacent endpoint with a 100 ms budget uses provisioned concurrency on an alias; a cron job ignores the problem.
| Mitigation | What it removes | Limits and cost |
|---|---|---|
| Smaller package, lazy init | Download and Init time | Free |
| Language choice | Go and Rust start in tens of milliseconds; JVM and .NET take seconds without SnapStart; PHP through Bref adds about 250 ms (Bref docs) | Inference for Go and Rust, no page fetched for the numbers |
| SnapStart | Init time (Java 11+, Python 3.12+, .NET 8+ per the page read) | Published versions and aliases only; not with provisioned concurrency, EFS or ephemeral storage above 512 MB; uniqueness (random seeds, IDs, connections) must be re-established after restore |
| Provisioned concurrency | Cold starts for N environments | You pay for the idle environments; Init may run up to 15 minutes |
| Warmers (scheduled pings) | Cold starts for one environment per ping | Bref documents this for low traffic: a schedule event every 5 minutes |
| Cloud Run minimum instances | Scale-to-zero cold starts | Idle instances are billed at a lower rate |
Fix / how to use it: measure first (the INIT_REPORT log line carries Init Duration); shrink; then choose SnapStart or provisioned concurrency for the endpoints with a latency budget, not for the whole account.
Concurrency: reserved, provisioned, scaling rate Must-know
In plain words: Concurrency is how many invocations are running at the same instant. It is the number that decides your throughput, your bill and how hard you hit your database.
Common misunderstanding: "Concurrency equals requests per second." It is requests per second times duration in seconds (Little's law, and the formula in the AWS documentation): 5,000 requests per second at 200 ms is 1,000 concurrent executions, exactly the default account limit.
Definition: The account has a concurrency limit per Region (default 1,000). Reserved concurrency sets a maximum and also reserves that share for the function so others cannot take it; it is free. Provisioned concurrency pre-initialises environments. The concurrency scaling limit for a function is 1,000 new execution environments every 10 seconds. A function throttles with HTTP 429 (TooManyRequestsException) when it hits its ceiling. For SQS event sources, the mapping's maximum concurrency (2 to 1,000) caps how many function instances one queue can use and is independent of reserved concurrency.
5,000 rps x 0.2 s = 1,000 concurrent -> at the account limit, new requests throttle (429)
reserved concurrency 100 on function B -> B can never exceed 100
-> the rest of the account shares 900
SQS max concurrency 20 -> poller stops at 20 in-flight invocationsReal scenario: a batch job and an API share an account: without reserved concurrency a backlog drains concurrency and the API receives 429s. A queue consumer writing to a database with 100 connections is capped at 20 concurrent invocations so it can never open more than 20 pools.
| Control | What it does | Cost |
|---|---|---|
| Account limit (1,000 default) | Hard ceiling for all functions in a Region | Soft: request an increase |
| Reserved concurrency | Maximum and guaranteed minimum for one function | Free; counts against the account |
| Provisioned concurrency | Pre-initialised environments, up to a number you set | Billed while provisioned |
| SQS maximum concurrency | Per event source cap | Free |
| SQS provisioned mode | Dedicated pollers, faster scaling (up to 1,000 invokes per minute added) | Extra cost |
| Function scaling limit | 1,000 environments per 10 s per function | Hard |
Fix / how to use it: compute concurrency from rate and duration, set reserved concurrency for each critical and each dangerous function, and put maximum concurrency on every queue that feeds something fragile.
Event sources and triggers Must-know
In plain words: A function does nothing until an event asks. The event source decides how it arrives, how fast, how often and what happens on failure, so choosing the source is the real design decision.
Common misunderstanding: "S3 triggers are reliable and exactly once." They are asynchronous invokes, so at-least-once, and the function can see the same object event twice or events out of order.
Definition: Triggers push events into Lambda (S3, SNS, EventBridge, API Gateway, ALB, function URL, Cognito); event source mappings are Lambda-managed pollers (SQS, Kinesis, DynamoDB Streams, MSK, self-managed Kafka, Amazon MQ, DocumentDB) that read in batches. EventBridge adds rules that match patterns on a bus, EventBridge Scheduler for cron and rate expressions, Pipes for point-to-point integration with enrichment, and a schema registry (OpenAPI 3 and JSONSchema Draft4).
HTTP client -> API Gateway / ALB / function URL -> function (sync)
object S3 object created -> function (async, retry x2, DLQ)
fan-out publisher -> SNS topic -> N SQS queues -> N functions (poll)
bus producer -> EventBridge bus -> rule (pattern) -> target(s)
stream Kinesis shard / DynamoDB Stream -> function (ordered per shard)
time EventBridge Scheduler (cron, rate) -> functionReal scenario: user uploads a photo (S3 event), the function writes a thumbnail and publishes PhotoProcessed to an EventBridge bus; rules route it to a search indexer and a notifier; a nightly schedule compacts old rows.
| Source | Invocation type | Ordering | Failure handling |
|---|---|---|---|
| API Gateway, ALB, function URL | Sync | None | Caller sees 5xx and retries; function URLs have auth AWS_IAM or NONE |
| S3, SNS, EventBridge | Async | None | Lambda retries, DLQ or destination |
| SQS standard | Poll | Best effort | Visibility timeout, redrive DLQ, ReportBatchItemFailures |
| SQS FIFO | Poll | Per message group | Stop at first failure in a group |
| Kinesis, DynamoDB Streams | Poll | Per shard | A failing batch blocks the shard until it succeeds, expires or a bisect/destination setting moves on |
| EventBridge Scheduler | Async | Not applicable | Configurable retries and DLQ |
| MSK / Kafka | Poll | Per partition | Batch retry with on-failure destination |
Fix / how to use it: if the work must not be lost and may be slow, prefer SQS between producer and function over a direct async invoke: you gain a visible backlog, a DLQ with maxReceiveCount, and a concurrency cap. For the mechanics of queues see Competing Consumers & Scaling and Ordering & Partitioning.
Batch size, batch window and partial batch response Must-know
In plain words: Lambda hands your function a bundle of messages. If one is bad, by default the whole bundle is retried, including the good ones. A partial batch response lets you say which ones failed.
Common misunderstanding: "If my handler returns normally, everything succeeded." With ReportBatchItemFailures enabled, a normal return containing an empty batchItemFailures means all succeeded, but a return that lists IDs keeps only those. And if the handler throws, "the entire batch is considered a complete failure" (AWS documentation).
Definition: BatchSize is the maximum records per invocation; MaximumBatchingWindowInSeconds (0 to 300) is how long to gather records. Lambda invokes when the window expires, the payload quota is reached or the batch size is reached. SQS defaults to 10 messages and a 0 second window; with a window and low traffic Lambda may wait up to 20 seconds. Enable partial batch response with FunctionResponseTypes: ReportBatchItemFailures and return {"batchItemFailures":[{"itemIdentifier":"<messageId>"}]}.
batch of 5: id1 ok, id2 FAIL, id3 ok, id4 FAIL, id5 ok
without partial response: function errors -> all 5 reappear after visibility timeout
with ReportBatchItemFailures:
return { batchItemFailures: [id2, id4] } -> Lambda deletes id1 id3 id5
id2 and id4 reappear after the visibility timeout, count one more receiveReal scenario: a 10-message batch where one message has malformed JSON: without the response, nine good messages are processed again each attempt until the bad one reaches the DLQ after maxReceiveCount; with it, only the bad one cycles.
| Setting | Meaning | Value |
|---|---|---|
BatchSize | Records per invocation | Default 10 on SQS; larger batches (up to 10,000) need a batch window |
MaximumBatchingWindowInSeconds | Gather time | 0 to 300 s; FIFO needs provisioned mode for a window |
ScalingConfig.MaximumConcurrency | Cap on concurrent invokes from one SQS source | 2 to 1,000 |
FunctionResponseTypes | ReportBatchItemFailures | Per mapping |
| FIFO rule | Stop at first failure, return it and everything after it | Keeps order inside a group |
| Poller scaling (standard queue) | Starts at 5 concurrent invokes, adds up to 300 per minute, max 1,250 per mapping | Provisioned mode raises it |
Fix / how to use it: the Go handler in this chapter returns events.SQSEventResponse with the failed MessageIds, treats FIFO specially, and returns the rest of the batch when the deadline approaches. See Go.
Retries, DLQs and destinations Must-know
In plain words: Something will fail. Decide where the failed event goes so a human or a replay job can find it, instead of losing it silently.
Common misunderstanding: "A DLQ on the function catches failed SQS messages." For SQS the DLQ belongs to the source queue (a redrive policy with maxReceiveCount), not to the function. A function-level DLQ or destination applies to asynchronous invocations only.
Definition: For asynchronous invocation Lambda retries a function error twice by default, waiting one minute and then two; for throttling and 5xx it retries for up to 6 hours with an interval growing from 1 second to a maximum of 5 minutes. Events that expire or fail all attempts are discarded unless you configure a dead-letter queue (SQS standard queue or SNS standard topic, event body only) or an on-failure destination (SQS, SNS, Lambda, EventBridge, S3; the JSON invocation record with the error). An on-success destination records successes. FIFO queues and FIFO topics are not supported as destinations.
async event -> attempt 1 fails
-> wait 1 min -> attempt 2 fails
-> wait 2 min -> attempt 3 fails
-> on-failure destination or DLQ receives the record
SQS message -> receive count 1..N -> exceeds maxReceiveCount -> source queue's DLQReal scenario: an S3 upload handler fails for a corrupt file; after three tries the record lands in an SQS destination with the S3 key and the error, where a nightly job and an alert read it.
| Mechanism | Applies to | Captures | Notes |
|---|---|---|---|
SQS redrive DLQ + maxReceiveCount | SQS event source | The original message | Configure on the queue; give it long retention |
| Function DLQ | Async invokes | The event only | SQS or SNS standard |
| On-failure destination | Async invokes | Event, error, attempt count | Preferred over DLQ for richer data |
| Stream on-failure destination | Kinesis, DynamoDB, Kafka mappings | Metadata of the failed batch | Not the records themselves |
| Maximum retry attempts / event age | Async and stream mappings | Limits the retries | Set to avoid poison batches blocking a shard |
Fix / how to use it: set the DLQ, alarm on its depth, document the replay procedure, and keep the retry budget finite. The patterns are in Dead-Letter Queue and Retry, Backoff & Delayed Delivery.
Idempotency under at-least-once delivery Must-know
In plain words: The platform may give you the same event twice, so doing the work twice must be harmless.
Common misunderstanding: "The MessageId is a good idempotency key." A redelivery keeps it, but a producer that retries a send creates a new message with a new MessageId for the same business event. The key must come from the business event (order id, invoice id, request id).
Definition: AWS states that event source mappings "process each event at least once, and duplicate processing of records can occur" and recommends idempotent code. The standard protocol: claim a key with a conditional write, do the work, mark it complete; a duplicate finds the key and returns success; a crash leaves an expired lease that another invocation can take over. Powertools for AWS Lambda ships this as an idempotency utility backed by DynamoDB.
delivery 1: Claim(key) -> Claimed -> work -> Complete(key) -> delete message
delivery 2: Claim(key) -> Done -> delete message
crash: Claim(key) -> Claimed -> (function dies)
retry: Claim(key) -> InProgress until the lease expires -> then ClaimedReal scenario: a charge-card job runs twice after a timeout; the second run finds Done and skips, and the payment API also receives the same Idempotency-Key header. Link: API Idempotency and Idempotent Consumers & the Inbox Pattern.
| Store | Atomic claim | Notes |
|---|---|---|
| DynamoDB | PutItem with attribute_not_exists(pk) and a TTL attribute | The Powertools default |
| PostgreSQL / MySQL | INSERT ... ON CONFLICT DO NOTHING / INSERT IGNORE, row count tells who won | Same transaction as the business write gives atomicity |
| Redis | SET key value NX PX lease | Fast; lease only, durability depends on config |
| In-memory map | Per environment only | Tests and local adapter only |
CREATE TABLE idempotency_keys (
idempotency_key text PRIMARY KEY,
status text NOT NULL CHECK (status IN ('in_progress','completed')),
lease_until timestamptz NOT NULL,
expires_at timestamptz NOT NULL
);
-- claim: one winner. Zero rows returned means someone else holds a live key.
INSERT INTO idempotency_keys (idempotency_key, status, lease_until, expires_at)
VALUES ($1, 'in_progress', now() + interval '2 minutes', now() + interval '7 days')
ON CONFLICT (idempotency_key) DO UPDATE
SET lease_until = EXCLUDED.lease_until
WHERE idempotency_keys.status = 'in_progress' AND idempotency_keys.lease_until < now()
RETURNING idempotency_key;Fix / how to use it: see the Go idem package and the Laravel EnsureOnce middleware below. Keep records at least as long as the source can redeliver (SQS retention, up to 14 days).
Stateless by force: external state and connection pooling Must-know
In plain words: The function cannot keep your data between calls, so every piece of state lives somewhere else: a database, a cache or a bucket.
Common misunderstanding: "I can keep a global variable as a cache." You can as an optimisation, but it is per environment, may disappear any time and is different in every concurrent environment. It is not shared state.
Definition: Each concurrent invocation runs in its own environment, so 1,000 concurrent invocations can try to open 1,000 database connections. A relational database such as PostgreSQL or MySQL handles hundreds of connections, not thousands. The AWS documentation recommends Amazon RDS Proxy for functions that make frequent short database connections: "A database proxy manages a pool of shared database connections which enables your function to reach high concurrency levels without exhausting database connections." Alternatives: PgBouncer or Supavisor in front of PostgreSQL, the RDS Data API (HTTP) for Aurora, serverless-friendly databases such as DynamoDB, and a hard cap on function concurrency.
1,000 concurrent Lambdas x 1 connection each -> 1,000 connections -> too many connections
1,000 Lambdas -> RDS Proxy (pool of 50) -> 50 connections to the databaseReal scenario: a traffic spike takes an API from 20 to 400 concurrent invocations; the database hits max_connections and every function fails with FATAL: sorry, too many clients already. Pooling or a concurrency cap would have prevented it. Details of pooling: Connection Pooling.
| Option | Helps with | Costs |
|---|---|---|
| RDS Proxy | Connection count, failover pinning | Hourly charge based on database size |
| PgBouncer in transaction mode | Connection count | You run it; prepared statements and session state limits |
| RDS Data API | No connections at all | HTTP latency, payload limits |
| Reserved concurrency / SQS max concurrency | Limits parallelism | Lower throughput |
| DynamoDB or other HTTP-based stores | No pooling issue | Different data model |
| Redis for sessions and locks | Shared state | Another dependency; see Redis |
Fix / how to use it: put a pool or a cap between functions and the database before the first launch, and reuse the client created at Init.
Orchestration and choreography Important
In plain words: One function should do one small job. For a multi-step process either a conductor tells each step what to do (orchestration) or each step reacts to events (choreography).
Common misunderstanding: "A function can wait for the next step." You pay for waiting, you are limited by the timeout, and the environment can be recycled. Long waits belong in a workflow service.
Definition: AWS Step Functions runs state machines written in Amazon States Language. Standard workflows have exactly-once execution semantics and can run up to one year (documented rate: 2,000 executions per second); Express workflows are at-least-once, run up to five minutes and reach 100,000 executions per second. Azure Durable Functions gives code-first orchestration with checkpointing; Temporal gives the same model on your own infrastructure (see Durable Workflows & Jobs and Saga Pattern). Choreography uses EventBridge rules and event patterns so services react independently, with the schema registry as the contract.
orchestration: Step Functions -> validate -> charge -> reserve -> ship
(retries, catch, compensation in the state machine)
choreography: OrderPlaced -> EventBridge rule 1 -> billing
-> EventBridge rule 2 -> inventory
-> EventBridge rule 3 -> emailReal scenario: an order saga with compensation on failure uses a Standard workflow; a high-volume IoT transform that is safe to repeat uses Express; a "something happened" notification fan-out uses EventBridge rules.
| Option | Strength | Weakness |
|---|---|---|
| Step Functions Standard | Visible history, exactly-once, long running | Priced by state transition |
| Step Functions Express | High rate, priced by duration | At-least-once, five minutes |
| Azure Durable Functions | Orchestrator code | Deterministic-code constraints |
| Temporal | Portable, rich semantics | You run or buy it |
| EventBridge rules (choreography) | Loose coupling | Flow is implicit; debugging needs tracing |
| One function calling another synchronously | Simple | Double billing while waiting, coupled failures |
Fix / how to use it: orchestrate when you need compensation and visibility; choreograph when consumers are independent; never chain functions synchronously.
Other platforms and their constraints Important
In plain words: The same idea is packaged differently on each platform, and the differences are limits you must design around.
Common misunderstanding: "All serverless platforms behave like Lambda." Cloudflare Workers has no container at all, Cloud Run serves many requests per instance, and Vercel bills active CPU time.
Definition and limits as documented (pages read for this chapter):
| Platform | Model | Limits worth knowing |
|---|---|---|
| AWS Lambda | One request per environment, microVM | 30 minute timeout, 6 MB sync payload, 10 GB image |
| Google Cloud Run (services, functions, jobs) | Container; many requests per instance | Concurrency per instance default 80 times vCPUs (CLI), up to 1,000; scale to zero or minimum instances; billed per 100 ms |
| Azure Functions | Functions on Consumption, Flex Consumption or Premium plans | Not fetched for this chapter (the Microsoft pages were unreachable); check the hosting plan documentation |
| Cloudflare Workers | V8 isolates in a shared runtime | 128 MB per isolate; CPU time 10 ms on Free, up to 5 minutes on Paid (default 30 s); subrequests 50 (Free) or 10,000 (Paid) per request; no VM cold start |
| Vercel Functions | Functions behind a deployment | Default duration 300 s; Pro maximum 800 s; request body 4.5 MB by default; timeout returns 504 FUNCTION_INVOCATION_TIMEOUT |
| Netlify Functions | Functions on AWS Lambda behind Netlify | Not fetched; check the limits page |
| Fly Machines | Fast-booting VMs with a REST API | Start usually "well under a second"; you stop and start Machines yourself or let the proxy do it |
| Knative Serving | Kubernetes service with request-based autoscaling | Scale to zero configurable; runs on your cluster |
Workers: request -> existing V8 runtime -> new isolate (milliseconds) -> your code
Lambda: request -> microVM sandbox -> runtime -> your code
Cloud Run: request -> existing instance with free concurrency? yes -> serve
no -> start instanceReal scenario: a Cloudflare Worker rewrites headers and calls an origin (CPU time tiny); a Cloud Run service serves a legacy Laravel API with concurrency 10; Vercel hosts a Next.js app whose routes are functions.
Fix / how to use it: read the CPU, memory, duration and payload limits of the platform before choosing; they are the design constraints.
Edge functions Good to know
In plain words: Edge functions run in the CDN's locations close to the user, for small decisions that should not travel to a region.
Common misunderstanding: "Edge is just faster Lambda." Edge runtimes are restricted (isolates, small CPU budgets, limited APIs) and data still lives in a region, so a function at the edge that calls a distant database is slower, not faster.
Definition: Cloudflare Workers, Lambda@Edge and CloudFront Functions, Vercel's Edge runtime and Fastly Compute run code at CDN locations. Typical jobs: redirects, A/B bucketing, auth token checks, header rewrites, personalisation of cached pages. See CDNs.
user (Tehran) -> edge location (near) -> function: check cookie, rewrite -> cache hit
-> miss: origin in one regionReal scenario: rewrite / to a localised path from the Accept-Language header at the edge; verify a JWT signature before forwarding.
| Concern | Edge function | Regional function |
|---|---|---|
| Latency to user | Lowest | Region distance |
| Access to a regional database | Slow or replicated | Fast |
| CPU and memory budget | Small | Large |
| Libraries | Restricted APIs | Full runtime |
Fix / how to use it: keep edge code stateless, small and free of regional calls; use KV or cache for configuration.
Cost model: when serverless is cheaper or more expensive Must-know
In plain words: You pay a small price per request plus a price for every GB-second the function holds memory. Idle costs nothing; busy costs per unit of work.
Common misunderstanding: "Serverless cost is the Lambda line." The bill also has API Gateway per request, NAT gateway hours and data processing for VPC functions, CloudWatch logs, DynamoDB or SQS requests, and egress (data leaving the provider). For chatty workloads these can exceed the compute.
Definition: Lambda's pricing page states that Lambda is "priced per request and execution duration" with duration measured in GB-seconds and a free tier of one million requests and 400,000 GB-seconds per month. The per-unit prices were template placeholders in the page I fetched, so the numbers below use assumed round prices of 0.20 per million requests and 0.0000166667 per GB-second (the long-published first-tier x86 figures; verify on the pricing page before using them). The formula is monthly = max(0, requests - free) / 1e6 * pricePerMillion + max(0, requests * seconds * GB - freeGBs) * pricePerGBs.
Example A (spiky API): 2M requests/month, 120 ms, 512 MB
GB-s = 2,000,000 x 0.12 x 0.5 = 120,000 -> inside the free 400,000 GB-s
requests: (2M - 1M) / 1M x 0.20 = 0.20 -> total about 0.20 per month
Example B (steady): 100M requests/month, 200 ms, 1 GB
GB-s = 100M x 0.2 x 1 = 20,000,000
requests (100M - 1M) / 1M x 0.20 = 19.80
duration (20M - 0.4M) x 0.0000166667 = 326.67 -> about 346 per month
average rate 100M / 2.592M s = 38.6 rps; concurrency = 38.6 x 0.2 = 7.7
-> about 8 busy environments around the clock; a few 1 GB instances usually cost lessReal scenario: a webhook receiver, a nightly job and an internal tool are cheaper on functions; a 40 rps API with 200 ms handlers running all day is a candidate for containers. The Go costmodel package encodes the same arithmetic with prices as inputs.
| Factor | Pushes toward serverless | Pushes toward containers |
|---|---|---|
| Utilisation | Under about 10 to 20 percent average | Above about 40 percent steady (inference, depends on prices) |
| Traffic shape | Spiky, bursty, event driven | Flat |
| Duration per request | Short | Long (duration is the bill) |
| Memory per request | Small | Large |
| Egress and NAT | Small payloads | Large; costs the same either way, plus NAT for VPC functions |
| Operations staff | Small team | Platform team available |
| Hidden lines | API Gateway, logs, NAT | Idle capacity, patching |
Fix / how to use it: compute break-even with real prices (BreakEvenRequests in the snippet), include every line item, and revisit when traffic changes. Cap concurrency to cap the bill during an attack.
Limits and gotchas Important
In plain words: Serverless platforms have sharp edges that appear exactly when you scale.
Common misunderstanding: "I will find out about limits in production." Most of them are documented numbers you can design against.
Definition and catalogue:
| Gotcha | What happens | Mitigation |
|---|---|---|
| Payload limit | Sync 6 MB, async 1 MB on Lambda; Laravel's SQS overflow stores payloads of at least 1 MB in a cache store and sends a pointer; Vercel body 4.5 MB | Pass references (S3 key), not blobs; presigned URLs |
| Timeout | Function killed at the timeout; SQS visibility timeout shorter than the function means the message is delivered again while it runs | Set visibility timeout above the function timeout; keep work chunked |
| VPC attachment | Functions in a VPC use Hyperplane ENIs, lose internet access unless the VPC has NAT or endpoints; ENI quota 3,000 per VPC | Use VPC endpoints, plan subnets, attach only when needed |
| Network egress | Billed; NAT gateways charge per hour and per GB | Gateway endpoints for S3 and DynamoDB |
| Throttling | 429 when concurrency is exhausted; async retried for up to 6 hours | Reserved concurrency, queues |
| Logs | Every print costs money and latency | Structured, sampled logs |
| Clock and time | Handler returns while background goroutines freeze | Wait for work before returning |
| Deployment size | 50 MB zipped, 250 MB unzipped | Layers, container images up to 10 GB |
Observability. Enable AWS X-Ray active tracing (Active or PassThrough modes) or the OpenTelemetry Lambda layer (AWS Distro for OpenTelemetry), emit structured logs with the request id, and alarm on throttles, errors, IteratorAge for streams, queue age and DLQ depth. See Observability.
Local testing. Unit-test the handler as a plain function (no AWS calls); run it behind a local HTTP adapter; use AWS SAM (sam local invoke, sam local start-api) for event shapes, and LocalStack for emulated services. None of them reproduces concurrency, throttling or IAM faithfully, so keep one real-account smoke test.
Fix / how to use it: keep a checklist of limits next to the design; most outages are one of the rows above.
Security Important
In plain words: Every function has its own identity and its own inputs; give it only what it needs and distrust every event.
Common misunderstanding: "Events from our own queue are trusted." Event data originates from users somewhere (S3 object names, SNS messages, HTTP bodies), so event injection is real: an S3 key with shell metacharacters passed to a command, a JSON field concatenated into SQL.
Definition: The execution role is the IAM role the function assumes; apply least privilege: one role per function, specific resource ARNs, no wildcards. Secrets belong in Secrets Manager or Parameter Store (fetched at Init and cached with a refresh), not in environment variables in plain text. Validate and parameterise event input; set function URL auth to AWS_IAM unless a public endpoint is intended; restrict resource-based policies; enable code signing where policy demands it. Broader model: Security Foundations.
S3 event key "report; rm -rf /.csv" -> function runs "convert <key>" through a shell -> injection
S3 event key -> function passes it as an argument array, validates the extension -> safeReal scenario: a single shared admin role on twenty functions turns a bug in one into a breach of all; per-function roles confine it.
| Control | Practice |
|---|---|
| Execution role | One per function; deny by default; scope to ARNs and prefixes |
| Resource policy | Only the services and accounts that should invoke |
| Secrets | Secrets Manager, cached; rotate; never in logs |
| Input | Validate, parameterise, size-limit |
| Dependencies | Pin and scan; layers are code too |
| Network | VPC only when needed; endpoints over NAT |
Fix / how to use it: review each role as if the function were already compromised.
Portability and vendor lock-in Good to know
In plain words: The handler code ports; the events, the IAM, the triggers and the infrastructure definition do not.
Common misunderstanding: "Using containers makes Lambda portable." A container image changes packaging, not the event contract, the permissions or the integrations.
Definition: Portable layers: Knative (Serving and Eventing on Kubernetes) and OpenFaaS run functions on your own cluster; Cloud Run runs plain containers; frameworks such as Serverless Framework, AWS SAM, SST and the AWS CDK define infrastructure (still provider-specific). Bref's documentation has a vendor lock-in page arguing the application code stays portable because the framework runs the same on a server. Hexagonal design keeps the provider behind an interface.
handler(event) -> adapter (SQS event -> domain command) -> domain code (portable)
-> ports: Store, PublisherReal scenario: the domain package is unit-tested without any AWS type, and the cmd/lambda and cmd/local mains are two thin adapters; moving to Cloud Run changes only the adapter.
| Layer | Portability |
|---|---|
| Domain code | High |
| Handler signature and event types | Provider specific (aws-lambda-go events) |
| IAM and triggers | Provider specific |
| IaC (CDK, SAM, SST, Serverless Framework) | Tool and provider specific |
| Knative, OpenFaaS | Portable across Kubernetes |
Fix / how to use it: isolate the adapter, keep the domain free of provider types, and accept that integration code is the lock-in.
Event-driven design with queues Must-know
In plain words: Put a queue between steps so one slow or failing step cannot block the others, and let each consumer take what it can handle.
Common misunderstanding: "Fan-out means publishing to many functions directly." Direct fan-out from SNS to Lambda loses the buffer; SNS to SQS to Lambda gives each consumer its own queue, DLQ, retry policy and concurrency cap.
Definition: The standard pattern is publish to an SNS topic or EventBridge bus, subscribe one SQS queue per consumer, and attach one function per queue. Ordering: standard queues are best effort; SQS FIFO orders within a message group and caps concurrent invocations at the number of group IDs; Kinesis orders per shard (partition key). Backpressure: the queue grows instead of the consumer failing; reserved or maximum concurrency bounds the drain rate; alarm on queue age. Related: Backpressure & Flow Control, Event-Driven Architecture, Transactional Outbox.
order service -> commit order + outbox row -> relay -> SNS topic OrderPlaced
SNS -> queue billing -> Lambda (max 20) -> DB
SNS -> queue email -> Lambda -> SES
SNS -> queue search -> Lambda -> index
a spike of 10,000 orders: queues absorb it; billing drains at 20 concurrent; nothing is lostReal scenario: Black Friday traffic: the API stays fast because it only writes and publishes; the billing consumer drains at a controlled rate.
| Need | Tool | Detail |
|---|---|---|
| Fan-out | SNS to SQS to Lambda | One queue per consumer |
| Routing by content | EventBridge rules | Patterns on event fields |
| Strict order per entity | SQS FIFO with MessageGroupId, or Kinesis partition key | Concurrency limited by number of groups or shards |
| Buffering | SQS | Visible depth and age |
| Throttling downstream | Maximum concurrency, reserved concurrency | Drain at a safe rate |
| Replay | Kinesis retention, EventBridge archive, DLQ redrive | Plan it before you need it |
Fix / how to use it: one queue per consumer, DLQ per queue, a concurrency cap sized from the downstream limit, an idempotent consumer.
Mechanics
Knobs and where they live
| Knob | Where | Default | Notes |
|---|---|---|---|
| Function timeout | Function configuration | 3 s when created from the console (general knowledge) | Max 1,800 s |
| Memory | Function configuration | 128 MB | CPU scales with it |
Ephemeral storage /tmp | Function configuration | 512 MB | Up to 10,240 MB |
ReservedConcurrentExecutions | Function | None | Both a cap and a reservation |
| Provisioned concurrency | Alias or version | 0 | Billed |
BatchSize | Event source mapping | SQS 10 | Window needed above 10 |
MaximumBatchingWindowInSeconds | Event source mapping | 0 for SQS | Up to 300 |
FunctionResponseTypes | Event source mapping | Empty | ReportBatchItemFailures |
ScalingConfig.MaximumConcurrency | SQS mapping | None | 2 to 1,000 |
| SQS visibility timeout | Queue | 30 s | Set above the function timeout |
maxReceiveCount | Queue redrive policy | None | Moves to the DLQ |
Async MaximumRetryAttempts, MaximumEventAgeInSeconds | Function event invoke config | 2 retries, 6 hours | Lower to fail fast |
Error names and codes you will see
| Error | Meaning | What to do |
|---|---|---|
HTTP 429 TooManyRequestsException | Concurrency or rate exhausted | Reserved concurrency, queue, backoff |
| HTTP 502 from API Gateway | Malformed function response or crash | Return the documented shape; check logs |
HTTP 504 (API Gateway, Vercel FUNCTION_INVOCATION_TIMEOUT) | Integration or function timeout | Shorten work, async pattern |
Task timed out after N seconds | Function timeout | Raise timeout or chunk work |
INIT_REPORT ... Status: timeout | Init exceeded 10 s | Lighter init, SnapStart, provisioned concurrency |
SnapStartTimeoutException | Restore exceeded its limit | Shorten after-restore hooks |
Runtime.ExitError | Process exited unexpectedly | Check panics, OOM |
| Out of memory (Max Memory Used equals memory size) | Memory exhaustion | Raise memory |
DestinationDeliveryFailures metric | Lambda could not write to the destination | Fix permissions or use a standard queue |
Cloudflare Error 1102 Worker exceeded resource limits | CPU or memory limit | Stream bodies, raise CPU limit on Paid |
FATAL: sorry, too many clients already (PostgreSQL) | Connection exhaustion | Pool or cap concurrency |
The visibility timeout arithmetic
function timeout 60 s, SQS visibility timeout 30 s
t=0 message received, hidden for 30 s
t=30 still running (needs 45 s) -> message visible again
t=31 another environment receives it -> duplicate in flight
t=45 first run finishes and deletes using an old receipt handle -> may fail
rule: visibility timeout >= function timeout (plus batch window), commonly several times largerGo
The module uses github.com/aws/aws-lambda-go (v1.55.1 at the time of writing; import paths github.com/aws/aws-lambda-go/lambda and .../events). Handlers are plain functions; lambda.Start runs the Runtime API loop.
Before
A handler that fails the whole batch on one bad message, rebuilds its HTTP client per record and repeats side effects on redelivery.
// Before: a Lambda handler that treats an SQS batch as all-or-nothing and
// rebuilds its dependencies on every invocation. It "works" in a demo and
// fails in production in three ways: one bad message re-runs the whole batch,
// a retry repeats side effects, and every call pays for client construction.
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)
type order struct {
ID string `json:"id"`
Cents int64 `json:"cents"`
}
func handler(ctx context.Context, ev events.SQSEvent) error {
for _, rec := range ev.Records {
// New client per invocation: no connection reuse, extra latency and cost.
client := &http.Client{Timeout: 5 * time.Second}
var o order
if err := json.Unmarshal([]byte(rec.Body), &o); err != nil {
// Returning an error fails the WHOLE batch: the nine good
// messages become visible again and are processed twice.
return fmt.Errorf("bad message %s: %w", rec.MessageId, err)
}
// Side effect with no idempotency key: a retry charges twice.
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, "https://payments.example.com/charge", nil)
if _, err := client.Do(req); err != nil {
return err
}
}
return nil
}
func main() { lambda.Start(handler) }After
An idempotency ledger with a lease, a batch handler returning SQSEventResponse, FIFO handling, a deadline reserve, panic recovery, and an entry point that builds everything at Init.
// Package idem is a small idempotency ledger for at-least-once event sources.
//
// Lambda event source mappings, SQS and asynchronous invokes all deliver an
// event at least once, so a handler must be able to see "I have already done
// this" before it repeats a side effect. The Store interface is the contract;
// production code backs it with a conditional write (DynamoDB PutItem with
// attribute_not_exists, or an INSERT ... ON CONFLICT DO NOTHING in SQL).
package idem
import (
"context"
"errors"
"sync"
"time"
)
// State is the lifecycle of one idempotency key.
type State int
const (
// Claimed means this caller now owns the work and must finish or release it.
Claimed State = iota
// InProgress means another invocation holds an unexpired lease.
InProgress
// Done means the work finished earlier; skip it.
Done
)
// Store claims keys. Claim must be atomic: two concurrent callers with the same
// key must never both get Claimed.
type Store interface {
Claim(ctx context.Context, key string, lease time.Duration) (State, error)
Complete(ctx context.Context, key string, keep time.Duration) error
Release(ctx context.Context, key string) error
}
// ErrInProgress is returned by callers that choose to treat InProgress as
// "retry later" so the queue redelivers after its visibility timeout.
var ErrInProgress = errors.New("idempotency key in progress")
type entry struct {
done bool
expires time.Time
}
// Memory is an in-process Store for tests and for the local adapter. It is NOT
// safe across Lambda execution environments: each environment has its own map.
type Memory struct {
mu sync.Mutex
now func() time.Time
m map[string]entry
}
// NewMemory returns a Memory store using now as its clock.
func NewMemory(now func() time.Time) *Memory {
if now == nil {
now = time.Now
}
return &Memory{now: now, m: map[string]entry{}}
}
// Claim implements Store.
func (s *Memory) Claim(_ context.Context, key string, lease time.Duration) (State, error) {
s.mu.Lock()
defer s.mu.Unlock()
t := s.now()
if e, ok := s.m[key]; ok && t.Before(e.expires) {
if e.done {
return Done, nil
}
return InProgress, nil
}
// Missing or expired: take (or take over) the lease.
s.m[key] = entry{expires: t.Add(lease)}
return Claimed, nil
}
// Complete marks the key done and keeps the record for keep.
func (s *Memory) Complete(_ context.Context, key string, keep time.Duration) error {
s.mu.Lock()
defer s.mu.Unlock()
s.m[key] = entry{done: true, expires: s.now().Add(keep)}
return nil
}
// Release deletes an unfinished claim so a retry can start at once.
func (s *Memory) Release(_ context.Context, key string) error {
s.mu.Lock()
defer s.mu.Unlock()
if e, ok := s.m[key]; ok && !e.done {
delete(s.m, key)
}
return nil
}// Package sqsbatch turns an SQS batch into a partial batch response.
//
// It implements the contract of the Lambda SQS event source mapping with
// FunctionResponseTypes = ReportBatchItemFailures: the function returns the
// IDs of the messages that failed and Lambda deletes only the others.
package sqsbatch
import (
"context"
"errors"
"fmt"
"log/slog"
"time"
"github.com/aws/aws-lambda-go/events"
"academy/serverless-event-driven-compute/idem"
)
// Work processes one message body. It must be safe to run twice.
type Work func(ctx context.Context, msg events.SQSMessage) error
// Handler holds everything that is built once, in the Init phase.
type Handler struct {
Store idem.Store
Work Work
Log *slog.Logger
// Lease is how long a claim survives a crashed invocation. It must be at
// least the function timeout, otherwise a slow invocation loses its lock.
Lease time.Duration
// Keep is how long finished keys are remembered; it must cover the longest
// redelivery window (queue retention) of the source.
Keep time.Duration
// Reserve is the time kept free at the end of the invocation to report
// results instead of being killed mid-batch.
Reserve time.Duration
}
// Permanent marks an error that retrying will never fix. The handler still
// reports the message as failed so the queue can send it to its DLQ after
// maxReceiveCount receives; it only changes the log level and the metric.
type Permanent struct{ Err error }
func (p Permanent) Error() string { return "permanent: " + p.Err.Error() }
func (p Permanent) Unwrap() error { return p.Err }
// Handle is the function you pass to lambda.Start.
func (h *Handler) Handle(ctx context.Context, ev events.SQSEvent) (events.SQSEventResponse, error) {
var resp events.SQSEventResponse
fifoFailed := false
for i, rec := range ev.Records {
fifo := rec.Attributes["MessageGroupId"] != ""
// FIFO rule: after the first failure, return that message and every
// unprocessed one, so order inside the group is kept.
if fifo && fifoFailed {
resp.BatchItemFailures = append(resp.BatchItemFailures, events.SQSBatchItemFailure{ItemIdentifier: rec.MessageId})
continue
}
// Out of time: report the rest as failed rather than lose the response.
if dl, ok := ctx.Deadline(); ok && time.Until(dl) < h.Reserve {
for _, r := range ev.Records[i:] {
resp.BatchItemFailures = append(resp.BatchItemFailures, events.SQSBatchItemFailure{ItemIdentifier: r.MessageId})
}
h.Log.Warn("deadline near, returning rest of batch", "remaining", len(ev.Records)-i)
return resp, nil
}
if err := h.one(ctx, rec); err != nil {
resp.BatchItemFailures = append(resp.BatchItemFailures, events.SQSBatchItemFailure{ItemIdentifier: rec.MessageId})
if fifo {
fifoFailed = true
}
var perm Permanent
level := slog.LevelWarn
if errors.As(err, &perm) {
level = slog.LevelError
}
h.Log.Log(ctx, level, "message failed", "id", rec.MessageId, "err", err)
}
}
return resp, nil
}
// one runs the claim / work / complete protocol for a single message.
func (h *Handler) one(ctx context.Context, rec events.SQSMessage) (err error) {
// The key must come from the business event, not from the delivery: a
// redelivery keeps MessageId, but a producer retry creates a new one.
key := rec.MessageAttributes["idempotencyKey"].StringValue
if key == nil || *key == "" {
return Permanent{Err: errors.New("missing idempotencyKey attribute")}
}
state, err := h.Store.Claim(ctx, *key, h.Lease)
if err != nil {
return fmt.Errorf("claim: %w", err)
}
switch state {
case idem.Done:
return nil // duplicate delivery: success, delete the message
case idem.InProgress:
return idem.ErrInProgress // another invocation is on it; retry later
}
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panic: %v", r)
}
if err != nil {
_ = h.Store.Release(context.WithoutCancel(ctx), *key)
}
}()
if err = h.Work(ctx, rec); err != nil {
return err
}
return h.Store.Complete(ctx, *key, h.Keep)
}package sqsbatch
import (
"context"
"encoding/json"
"errors"
"github.com/aws/aws-lambda-go/events"
)
// EchoWork is a demo Work: it accepts JSON objects with a non-empty "id" and
// fails on anything else, which is enough to exercise partial failures.
func EchoWork(_ context.Context, msg events.SQSMessage) error {
var v struct {
ID string `json:"id"`
}
if err := json.Unmarshal([]byte(msg.Body), &v); err != nil {
return Permanent{Err: err}
}
if v.ID == "" {
return errors.New("empty id")
}
return nil
}// Command lambda is the deployable entry point: everything expensive is built
// in init-time package state, and only Handle runs per invocation.
package main
import (
"log/slog"
"os"
"time"
"github.com/aws/aws-lambda-go/lambda"
"academy/serverless-event-driven-compute/idem"
"academy/serverless-event-driven-compute/sqsbatch"
)
// h is built once per execution environment (Init phase) and reused by every
// invocation that environment serves. Put SDK clients, DB pools and parsed
// configuration here, never inside the handler.
var h = newHandler()
func newHandler() *sqsbatch.Handler {
return &sqsbatch.Handler{
// Replace idem.NewMemory with a DynamoDB- or SQL-backed Store in a
// real deployment: memory is per environment, not shared.
Store: idem.NewMemory(nil),
Work: sqsbatch.EchoWork,
Log: slog.New(slog.NewJSONHandler(os.Stdout, nil)),
Lease: 2 * time.Minute, // at least the function timeout
Keep: 7 * 24 * time.Hour,
Reserve: 2 * time.Second,
}
}
func main() { lambda.Start(h.Handle) }Unit tests call the handler directly, without AWS: partial failures, duplicate and producer-retry keys, FIFO stop, panic, deadline, missing key, lease takeover and a concurrent claim race.
package sqsbatch
import (
"context"
"errors"
"io"
"log/slog"
"testing"
"time"
"github.com/aws/aws-lambda-go/events"
"academy/serverless-event-driven-compute/idem"
)
func quiet() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) }
func msg(id, key, body string, fifo bool) events.SQSMessage {
m := events.SQSMessage{
MessageId: id, Body: body,
MessageAttributes: map[string]events.SQSMessageAttribute{
"idempotencyKey": {StringValue: &key, DataType: "String"},
},
Attributes: map[string]string{},
}
if fifo {
m.Attributes["MessageGroupId"] = "g1"
}
return m
}
func newH(work Work) (*Handler, *idem.Memory) {
st := idem.NewMemory(nil)
return &Handler{Store: st, Work: work, Log: quiet(), Lease: time.Minute, Keep: time.Hour}, st
}
func ids(r events.SQSEventResponse) []string {
var out []string
for _, f := range r.BatchItemFailures {
out = append(out, f.ItemIdentifier)
}
return out
}
func TestPartialBatchReportsOnlyFailures(t *testing.T) {
h, _ := newH(EchoWork)
ev := events.SQSEvent{Records: []events.SQSMessage{
msg("m1", "k1", `{"id":"a"}`, false),
msg("m2", "k2", `not json`, false),
msg("m3", "k3", `{"id":"c"}`, false),
msg("m4", "k4", `{"id":""}`, false),
}}
resp, err := h.Handle(context.Background(), ev)
if err != nil {
t.Fatal(err)
}
got := ids(resp)
if len(got) != 2 || got[0] != "m2" || got[1] != "m4" {
t.Fatalf("failures = %v, want [m2 m4]", got)
}
}
func TestDuplicateDeliveryDoesNotRepeatSideEffect(t *testing.T) {
calls := 0
h, _ := newH(func(context.Context, events.SQSMessage) error { calls++; return nil })
ev := events.SQSEvent{Records: []events.SQSMessage{msg("m1", "same", "{}", false)}}
for i := 0; i < 3; i++ {
if resp, _ := h.Handle(context.Background(), ev); len(resp.BatchItemFailures) != 0 {
t.Fatalf("delivery %d failed: %v", i, ids(resp))
}
}
if calls != 1 {
t.Fatalf("side effect ran %d times, want 1", calls)
}
}
func TestSameKeyDifferentMessageIDIsStillDuplicate(t *testing.T) {
calls := 0
h, _ := newH(func(context.Context, events.SQSMessage) error { calls++; return nil })
_, _ = h.Handle(context.Background(), events.SQSEvent{Records: []events.SQSMessage{msg("m1", "order-7", "{}", false)}})
_, _ = h.Handle(context.Background(), events.SQSEvent{Records: []events.SQSMessage{msg("m2", "order-7", "{}", false)}})
if calls != 1 {
t.Fatalf("calls = %d, want 1 (producer retry produced a new MessageId)", calls)
}
}
func TestFailureReleasesClaimSoRetryRuns(t *testing.T) {
attempts := 0
h, _ := newH(func(context.Context, events.SQSMessage) error {
attempts++
if attempts == 1 {
return errors.New("transient")
}
return nil
})
ev := events.SQSEvent{Records: []events.SQSMessage{msg("m1", "k", "{}", false)}}
if r, _ := h.Handle(context.Background(), ev); len(r.BatchItemFailures) != 1 {
t.Fatal("first attempt should fail")
}
if r, _ := h.Handle(context.Background(), ev); len(r.BatchItemFailures) != 0 {
t.Fatal("retry should succeed")
}
}
func TestInProgressIsReportedForRetry(t *testing.T) {
h, st := newH(EchoWork)
if s, _ := st.Claim(context.Background(), "busy", time.Minute); s != idem.Claimed {
t.Fatal("setup claim failed")
}
r, _ := h.Handle(context.Background(), events.SQSEvent{Records: []events.SQSMessage{msg("m1", "busy", `{"id":"x"}`, false)}})
if got := ids(r); len(got) != 1 || got[0] != "m1" {
t.Fatalf("failures = %v, want [m1]", got)
}
}
func TestFIFOStopsAtFirstFailureAndReturnsTheRest(t *testing.T) {
h, _ := newH(EchoWork)
ev := events.SQSEvent{Records: []events.SQSMessage{
msg("m1", "k1", `{"id":"a"}`, true),
msg("m2", "k2", `bad`, true),
msg("m3", "k3", `{"id":"c"}`, true),
msg("m4", "k4", `{"id":"d"}`, true),
}}
r, _ := h.Handle(context.Background(), ev)
got := ids(r)
if len(got) != 3 || got[0] != "m2" || got[1] != "m3" || got[2] != "m4" {
t.Fatalf("failures = %v, want [m2 m3 m4]", got)
}
}
func TestPanicBecomesFailureNotCrash(t *testing.T) {
h, _ := newH(func(context.Context, events.SQSMessage) error { panic("boom") })
r, err := h.Handle(context.Background(), events.SQSEvent{Records: []events.SQSMessage{msg("m1", "k", "{}", false)}})
if err != nil || len(r.BatchItemFailures) != 1 {
t.Fatalf("err=%v failures=%v", err, ids(r))
}
}
func TestDeadlineReturnsRemainingMessages(t *testing.T) {
h, _ := newH(EchoWork)
h.Reserve = time.Hour // any deadline is "too close"
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
ev := events.SQSEvent{Records: []events.SQSMessage{
msg("m1", "k1", `{"id":"a"}`, false), msg("m2", "k2", `{"id":"b"}`, false),
}}
r, _ := h.Handle(ctx, ev)
if len(r.BatchItemFailures) != 2 {
t.Fatalf("failures = %v, want both", ids(r))
}
}
func TestMissingKeyIsPermanentFailure(t *testing.T) {
h, _ := newH(EchoWork)
m := events.SQSMessage{MessageId: "m1", Body: `{"id":"a"}`}
r, _ := h.Handle(context.Background(), events.SQSEvent{Records: []events.SQSMessage{m}})
if len(r.BatchItemFailures) != 1 {
t.Fatal("message without key must be reported failed so the DLQ catches it")
}
}package idem
import (
"context"
"sync"
"sync/atomic"
"testing"
"time"
)
func TestLeaseExpiryAllowsTakeover(t *testing.T) {
now := time.Unix(1000, 0)
s := NewMemory(func() time.Time { return now })
ctx := context.Background()
if st, _ := s.Claim(ctx, "k", time.Minute); st != Claimed {
t.Fatal("first claim")
}
if st, _ := s.Claim(ctx, "k", time.Minute); st != InProgress {
t.Fatal("second claim inside lease must be InProgress")
}
now = now.Add(2 * time.Minute) // the first invocation crashed
if st, _ := s.Claim(ctx, "k", time.Minute); st != Claimed {
t.Fatal("expired lease must be claimable")
}
}
func TestConcurrentClaimHasOneWinner(t *testing.T) {
s := NewMemory(nil)
var wins atomic.Int32
var wg sync.WaitGroup
for i := 0; i < 50; i++ {
wg.Add(1)
go func() {
defer wg.Done()
if st, _ := s.Claim(context.Background(), "k", time.Minute); st == Claimed {
wins.Add(1)
}
}()
}
wg.Wait()
if wins.Load() != 1 {
t.Fatalf("winners = %d, want 1", wins.Load())
}
}
func TestDoneSurvivesUntilKeepExpires(t *testing.T) {
now := time.Unix(1000, 0)
s := NewMemory(func() time.Time { return now })
ctx := context.Background()
_, _ = s.Claim(ctx, "k", time.Minute)
_ = s.Complete(ctx, "k", time.Hour)
if st, _ := s.Claim(ctx, "k", time.Minute); st != Done {
t.Fatal("want Done")
}
now = now.Add(2 * time.Hour)
if st, _ := s.Claim(ctx, "k", time.Minute); st != Claimed {
t.Fatal("record should have expired")
}
}A local HTTP adapter runs the same handler for curl-based testing:
// Command local runs the same Handler behind plain HTTP so you can test it
// with curl and no AWS account. POST an SQS event JSON to /sqs and read back
// the partial batch response. This is the local-adapter pattern; it is not a
// replacement for AWS SAM or LocalStack when you need real event shapes.
package main
import (
"encoding/json"
"log"
"log/slog"
"net/http"
"os"
"time"
"github.com/aws/aws-lambda-go/events"
"academy/serverless-event-driven-compute/idem"
"academy/serverless-event-driven-compute/sqsbatch"
)
func main() {
h := &sqsbatch.Handler{
Store: idem.NewMemory(nil), Work: sqsbatch.EchoWork,
Log: slog.New(slog.NewTextHandler(os.Stdout, nil)),
Lease: time.Minute, Keep: time.Hour, Reserve: 0,
}
mux := http.NewServeMux()
mux.HandleFunc("POST /sqs", func(w http.ResponseWriter, r *http.Request) {
var ev events.SQSEvent
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&ev); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// A per-request deadline stands in for the Lambda function timeout.
ctx, cancel := contextWithTimeout(r, 15*time.Second)
defer cancel()
resp, err := h.Handle(ctx, ev)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(resp)
})
srv := &http.Server{Addr: "127.0.0.1:8080", Handler: mux, ReadHeaderTimeout: 5 * time.Second}
log.Println("listening on", srv.Addr)
log.Fatal(srv.ListenAndServe())
}package main
import (
"context"
"net/http"
"time"
)
func contextWithTimeout(r *http.Request, d time.Duration) (context.Context, context.CancelFunc) {
return context.WithTimeout(r.Context(), d)
}The cost model, with prices as inputs:
// Package costmodel compares pay-per-use compute with an always-on instance.
//
// Prices are inputs, never constants: provider prices change and differ per
// region and architecture. Read them from the provider's pricing page.
package costmodel
import "math"
// Prices holds the three numbers a FaaS bill is made of.
type Prices struct {
PerMillionRequests float64 // currency per 1,000,000 invocations
PerGBSecond float64 // currency per GB-second of duration
FreeRequests float64 // free invocations per month
FreeGBSeconds float64 // free GB-seconds per month
}
// Workload describes one month of traffic.
type Workload struct {
RequestsPerMonth float64
AvgDurationSec float64
MemoryMB float64
}
// GBSeconds is requests x duration x memory in GB (1 GB = 1024 MB).
func (w Workload) GBSeconds() float64 {
return w.RequestsPerMonth * w.AvgDurationSec * (w.MemoryMB / 1024)
}
// Monthly returns the FaaS bill for the workload, free tier applied.
func Monthly(p Prices, w Workload) float64 {
req := math.Max(0, w.RequestsPerMonth-p.FreeRequests) / 1e6 * p.PerMillionRequests
dur := math.Max(0, w.GBSeconds()-p.FreeGBSeconds) * p.PerGBSecond
return req + dur
}
// Concurrency is Little's law: average in-flight requests = rate x duration.
func Concurrency(requestsPerSecond, avgDurationSec float64) float64 {
return requestsPerSecond * avgDurationSec
}
// BreakEvenRequests returns the monthly request count at which FaaS costs the
// same as a fixed monthly price (ignoring the free tier), for a fixed duration
// and memory. Above it, an always-on instance is cheaper.
func BreakEvenRequests(p Prices, fixedMonthly, avgDurationSec, memoryMB float64) float64 {
perRequest := p.PerMillionRequests/1e6 + avgDurationSec*(memoryMB/1024)*p.PerGBSecond
if perRequest <= 0 {
return math.Inf(1)
}
return fixedMonthly / perRequest
}package costmodel
import (
"math"
"testing"
)
// Illustrative prices used only to exercise the arithmetic.
var p = Prices{PerMillionRequests: 0.20, PerGBSecond: 0.0000166667, FreeRequests: 1e6, FreeGBSeconds: 400000}
func near(a, b, eps float64) bool { return math.Abs(a-b) <= eps }
func TestConcurrencyLittle(t *testing.T) {
if got := Concurrency(5000, 0.2); !near(got, 1000, 1e-9) {
t.Fatalf("got %v want 1000", got)
}
if got := Concurrency(100, 0.5); !near(got, 50, 1e-9) {
t.Fatalf("got %v want 50", got)
}
}
func TestMonthlyFreeTier(t *testing.T) {
w := Workload{RequestsPerMonth: 500_000, AvgDurationSec: 0.1, MemoryMB: 512}
if got := Monthly(p, w); got != 0 {
t.Fatalf("inside free tier should be 0, got %v", got)
}
}
func TestMonthlyPaid(t *testing.T) {
// 100M requests x 200 ms x 1 GB = 20,000,000 GB-s.
w := Workload{RequestsPerMonth: 100e6, AvgDurationSec: 0.2, MemoryMB: 1024}
got := Monthly(p, w)
want := (100e6-1e6)/1e6*0.20 + (20e6-400000)*0.0000166667
if !near(got, want, 1e-6) {
t.Fatalf("got %v want %v", got, want)
}
}
func TestBreakEvenMovesWithDuration(t *testing.T) {
short := BreakEvenRequests(p, 100, 0.05, 512)
long := BreakEvenRequests(p, 100, 0.5, 512)
if !(short > long) {
t.Fatalf("shorter duration must break even at more requests: %v vs %v", short, long)
}
}The Go angle
Go is the easy case for cold starts: a static binary named bootstrap on the provided.al2023-style custom runtime (the Lambda Go handler page says the executable in a zip must be named bootstrap at the zip root), no VM to start, small memory. Initialise SDK clients in package-level variables or init(); the AWS page warns that init() has no context, so keep anything that needs one in lazy initialisation with sync.Once. Go's context.Context carries the invocation deadline: ctx.Deadline() is how the handler knows how much time is left, which the snippet uses to return the unprocessed part of a batch instead of being killed. Goroutines freeze when the handler returns, so wait for them (errgroup) before returning. Limit memory to what the GC needs; Lambda gives CPU proportional to memory, so a Go function at 128 MB gets a small CPU share, and raising memory can lower cost by shortening duration.
Laravel
Laravel does not run on Lambda by itself. Two projects package it: Bref (open source, PHP runtimes on Lambda; Laravel bridge, the Serverless Framework or its Lift plugin) and Laravel Vapor (Laravel's own serverless deployment platform "powered by AWS Lambda", with a vapor.yml). The Vapor site currently shows a banner about migrating from Vapor to Laravel Cloud; Vapor documentation remains available.
Before
A job written for a long-lived worker: no idempotency, no bounded timeout, no backoff.
<?php
namespace App\Jobs;
use App\Models\Invoice;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Http;
// Before: a job written for a long-lived worker. On SQS plus Lambda it is
// delivered at least once, so a redelivery after a timeout charges twice;
// there is no idempotency key, no bounded timeout and no backoff.
class SendInvoiceJob implements ShouldQueue
{
use Queueable;
public function __construct(public int $invoiceId) {}
public function handle(): void
{
$invoice = Invoice::findOrFail($this->invoiceId);
// The payment API cannot tell this call from a retry of itself.
Http::post('https://payments.example.com/charge', [
'amount' => $invoice->amount_cents,
'customer' => $invoice->customer_id,
])->throw();
$invoice->update(['status' => 'charged']);
}
}After
An idempotent job: a stable business key sent to the payment provider, ledger claim in the same transaction as the business write, bounded timeout, backoff, FIFO deduplicationId and messageGroup (Laravel 13 SQS FIFO support), and routing with Queue::route.
<?php
namespace App\Jobs;
use App\Jobs\Middleware\EnsureOnce;
use App\Models\Invoice;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Http;
// After: safe under at-least-once delivery on SQS (Bref or Laravel Vapor).
class ChargeInvoice implements ShouldQueue
{
use Queueable;
// Keep this below the SQS visibility timeout and the Lambda timeout.
public int $timeout = 25;
public int $tries = 5;
public function __construct(public int $invoiceId) {}
/** Seconds to wait before attempt 2, 3, 4... (exponential, capped). */
public function backoff(): array
{
return [10, 30, 120, 600];
}
/** Business identity of the effect, not of the delivery. */
public function idempotencyKey(): string
{
return "charge-invoice-{$this->invoiceId}";
}
/** SQS FIFO only: drop producer retries inside the 5 minute window. */
public function deduplicationId(): string
{
return $this->idempotencyKey();
}
/** SQS FIFO: serialize jobs for one customer, parallelize across customers. */
public function messageGroup(): string
{
return 'invoice-'.$this->invoiceId;
}
public function middleware(): array
{
return [new EnsureOnce($this->idempotencyKey())];
}
public function handle(): void
{
$invoice = Invoice::findOrFail($this->invoiceId);
// Pass the same key to the provider: it dedupes if our ledger row is
// lost between the charge and the commit.
Http::withHeaders(['Idempotency-Key' => $this->idempotencyKey()])
->timeout(10)
->post('https://payments.example.com/charge', [
'amount' => $invoice->amount_cents,
'customer' => $invoice->customer_id,
])
->throw();
$invoice->update(['status' => 'charged']);
}
}<?php
namespace App\Jobs\Middleware;
use Closure;
use Illuminate\Support\Facades\DB;
// Job middleware: run the job body at most once per business key, even when
// SQS delivers the message twice. The ledger row and the job's own database
// writes commit in one transaction, so a crash leaves neither behind.
class EnsureOnce
{
public function __construct(private string $key) {}
public function handle(object $job, Closure $next): void
{
DB::transaction(function () use ($job, $next) {
$inserted = DB::table('processed_jobs')->insertOrIgnore([
'idempotency_key' => $this->key,
'processed_at' => now(),
]);
if ($inserted === 0) {
// Duplicate delivery: finish without repeating the effect so
// the message is deleted from the queue.
$job->delete();
return;
}
$next($job);
});
}
}<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('processed_jobs', function (Blueprint $table) {
// The primary key is the claim: a second insert is a no-op.
$table->string('idempotency_key', 191)->primary();
$table->timestamp('processed_at');
$table->index('processed_at'); // for a periodic purge of old keys
});
}
public function down(): void
{
Schema::dropIfExists('processed_jobs');
}
};<?php
namespace App\Providers;
use App\Jobs\ChargeInvoice;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
// Laravel 13: send every ChargeInvoice to one named queue without
// calling onQueue() at each dispatch site.
Queue::route(ChargeInvoice::class, queue: 'invoices');
// Bref names Lift queues "<stack>-<construct>"; forward the logical
// queue name to the real SQS queue (Laravel 13.26 and later).
if ($stack = config('bref.stack_name')) {
Queue::forward(['invoices' => "$stack-invoices"], connection: 'sqs');
}
}
}<?php
// Excerpt of config/queue.php: the SQS connection as Laravel 13 documents it.
// There is no retry_after for SQS: the queue's own visibility timeout decides
// when an unfinished job reappears, so set it above the worker timeout.
return [
'default' => env('QUEUE_CONNECTION', 'sqs'),
'connections' => [
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'default'),
'suffix' => env('SQS_SUFFIX'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'after_commit' => true, // dispatch only after the DB transaction commits
],
],
'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
'database' => env('DB_CONNECTION', 'mysql'),
'table' => 'failed_jobs',
],
];<?php
use Illuminate\Support\Facades\Schedule;
// On a server a cron entry calls schedule:run every minute. On AWS Lambda an
// EventBridge schedule (see serverless.yml) plays that role. It fires from a
// single place, so onOneServer() is not needed; withoutOverlapping() still is,
// because a slow run can overlap the next minute.
Schedule::command('invoices:retry-failed')->everyFiveMinutes()->withoutOverlapping(10);
Schedule::command('idempotency:purge')->daily();<?php
namespace Tests\Feature;
use App\Jobs\ChargeInvoice;
use App\Models\Invoice;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Queue;
use Tests\TestCase;
class ChargeInvoiceTest extends TestCase
{
use RefreshDatabase;
public function test_redelivery_does_not_charge_twice(): void
{
Http::fake(['payments.example.com/*' => Http::response(['ok' => true])]);
$invoice = Invoice::factory()->create(['status' => 'open']);
// SQS delivers the same message twice (at-least-once).
ChargeInvoice::dispatchSync($invoice->id);
ChargeInvoice::dispatchSync($invoice->id);
Http::assertSentCount(1);
$this->assertSame('charged', $invoice->fresh()->status);
}
public function test_provider_receives_a_stable_idempotency_key(): void
{
Http::fake(['payments.example.com/*' => Http::response(['ok' => true])]);
$invoice = Invoice::factory()->create();
ChargeInvoice::dispatchSync($invoice->id);
Http::assertSent(fn ($request) => $request->hasHeader('Idempotency-Key', "charge-invoice-{$invoice->id}"));
}
public function test_job_is_routed_to_the_invoices_queue(): void
{
Queue::fake();
ChargeInvoice::dispatch(7);
Queue::assertPushedOn('invoices', ChargeInvoice::class);
}
}Deployment descriptors, Bref and Vapor:
# Bref (Serverless Framework) deployment of a Laravel app on AWS Lambda.
# The shape follows the Bref Laravel pages: an FPM function for HTTP, a worker
# for SQS (via the Lift queue construct) and a console function on a schedule.
service: invoices
provider:
name: aws
region: eu-west-1
environment:
QUEUE_CONNECTION: sqs
SQS_QUEUE: ${construct:invoices.queueUrl}
plugins:
- ./vendor/bref/bref
- serverless-lift
functions:
web:
handler: public/index.php
runtime: php-84-fpm
timeout: 28 # API Gateway HTTP API gives up at 30 s
events:
- httpApi: '*'
artisan:
handler: artisan
runtime: php-84-console
timeout: 720
events:
- schedule:
rate: rate(1 minute)
input: '"schedule:run"'
constructs:
invoices:
type: queue
maxConcurrency: 20 # protect the payment API and the database
worker:
handler: Bref\LaravelBridge\Queue\QueueHandler
runtime: php-84
timeout: 60# Laravel Vapor environment: the same ideas, expressed in Vapor's vocabulary.
id: 12345
name: invoices
environments:
production:
memory: 1024
cli-memory: 512
concurrency: 100 # web Lambda concurrency cap (also a cost cap)
queue-concurrency: 50 # queue Lambda concurrency cap
warm: 5 # pre-warm containers after deploy and every 5 minutes
queues:
- invoices: 10 # at most 10 concurrent jobs from this queue
scheduler: true
octane: false
build:
- 'composer install --no-dev'The Laravel angle
- Queues on SQS. Laravel 13's
sqsdriver needsaws/aws-sdk-php; there is noretry_afterfor SQS: the queue's default visibility timeout decides redelivery (Laravel queue documentation). Setafter_commitso a job is not dispatched before its data is committed. - Bref queue model. On Lambda you do not run
queue:work; SQS invokes a worker function (Bref\LaravelBridge\Queue\QueueHandler). Bref says it does not use the SQS retry and DLQ features but Laravel's own: jobs without$triesare attempted 3 times (not once asqueue:workdoes), failed jobs go tofailed_jobs, Laravel Horizon does not work on Lambda, and each queue has its own worker function with no priorities between queues. - FIFO. Laravel supports SQS FIFO and fair queues:
onGroup()ormessageGroup()sets the message group ID,deduplicationId()sets deduplication; without a group Laravel uses the queue name as the group. FIFO caveat: one group means one job at a time for the whole queue. - Vapor.
queue-concurrencyand per-queue limits (- invoices: 10) cap Lambda concurrency;warm: 5prewarms containers; the scheduler uses the DynamoDB cache driver to avoid overlap; the Vapor documentation states a single request or job may run for at most 15 minutes, which is the older Lambda limit and now lower than the AWS quotas page (30 minutes). Trust the stricter number until you verify the platform. - Scheduling. On Lambda an EventBridge schedule calls
schedule:runevery minute (Bref's cron page);onOneServer()is not needed because one place invokes it, but usewithoutOverlapping()and set the function timeout above the longest task. - Octane vs FPM. PHP-FPM boots the framework per request (Bref's FPM runtime keeps the process in the environment); Octane keeps Laravel booted: Bref's
OctaneHandlerwithBREF_LOOP_MAXrestarts the process after N requests, and Bref notes you still do not pay between requests because Lambda freezes the environment. Beware memory leaks and persistent database connections (setidle_in_transaction_session_timeouton PostgreSQL). - Cold starts for PHP. Bref reports about 250 ms added by its runtimes and about 0.2 percent of requests being cold on busy applications; exclude
node_modules, tests and assets from the package.
Solving the classic problems
A spike overloads the database
| Solution | How | Advantage | Cost or limit |
|---|---|---|---|
| Queue between API and worker | API writes to SQS; worker function drains | Buffer and visible backlog | Eventual completion |
| SQS maximum concurrency / reserved concurrency | Cap drain rate | Predictable load | Lower throughput |
| RDS Proxy or PgBouncer | Pool connections | Many functions, few connections | Extra component and fee |
Duplicate side effects
Use a business key, a conditional claim, and pass the key to the provider; see Idempotency. Test with the same event twice and with the same key under a different message id.
One poison message keeps cycling
Enable ReportBatchItemFailures, set maxReceiveCount and a DLQ, alarm on DLQ depth. Without the partial response one bad message makes nine good ones repeat each time.
Function waits for a slow dependency
Set an HTTP client timeout below the function timeout, use a circuit breaker for repeated failure (see Circuit Breaker and Timeouts, Retries & Jitter), and make slow work asynchronous.
Cold start hurts p99
Measure Init Duration; shrink the package; move work from Init to lazy paths; use SnapStart or provisioned concurrency for the endpoints that have a budget; consider a serverless container with minimum instances.
The bill surprises you
Set reserved concurrency as a ceiling, billing alarms, log retention, and review the non-Lambda lines (API Gateway, NAT, logs, egress). An attack on a public endpoint is a billing event too: add rate limiting and WAF (DDoS Protection).
The retry storm
Async retries, SQS redelivery and client retries multiply. Cap retries, use backoff with jitter, and prefer the queue to be the only retrying layer.
Ordering was assumed
Standard queues and async invokes do not order. Use FIFO with message groups or Kinesis partition keys, and design consumers so ordering matters only per entity.
Choosing
Which compute for which workload
| Workload | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Webhook receiver, low volume | Function | Queue behind it | No idle cost, spikes absorbed |
| Event glue between managed services | Function | EventBridge or SQS | Native integration |
| Spiky public API with relaxed latency | Function + API Gateway or function URL | Provisioned concurrency for hot paths | Scale to zero |
| Steady API, 40 percent or more utilisation | Containers or serverless containers | Autoscaling | Lower cost per request |
| Long jobs over 30 minutes | Containers, batch jobs, Step Functions | Chunking | Function limits |
| Connection-heavy database access | Containers, or functions + RDS Proxy | Concurrency cap | Pool pressure |
| Strict p99 under about 100 ms | Containers, or provisioned concurrency | Edge cache | Cold starts |
| Edge personalisation, redirects | Edge functions | KV | Latency |
| Orchestrated multi-step business flow | Step Functions or Temporal | Idempotent steps | Visibility, compensation |
| Portable, Kubernetes shop | Knative or OpenFaaS | CloudEvents | Avoid lock-in |
Sizing a queue consumer
inputs: peak 500 msg/s, handler 400 ms, batch 10, downstream allows 40 connections
concurrency = rate x duration, per message = 500 x 0.4 = 200 if one message per invoke
batch of 10 per invoke at ~1.5 s per batch -> 50 msg/s per environment -> 10 environments
cap with SQS maximum concurrency 40 (the database), reserved concurrency 50
visibility timeout >= 6 x function timeout is a common safe margin (practice, not from the page)In architecture: from a single process to a distributed system
Monolith: one process, one database
A Laravel or Go monolith deploys as one function (Bref FPM runtime or a Go API behind a function URL) or as one container on Cloud Run. The simplest correct move is to keep the monolith and offload the spiky edges: image processing on S3 events, emails and reports as queue jobs, a nightly job on EventBridge Scheduler. One database, so cap function concurrency and use a pool.
Modular monolith: boundaries without the network
Modules stay in one codebase but each background capability (billing jobs, search indexing) gets its own queue, its own function and its own concurrency cap and DLQ. The boundary is the queue contract; event shapes are versioned (see the schema registry) so a module can later become a service.
Microservices: functions as small services
Each service owns its data and publishes events; consumers subscribe through their own queues. Idempotent consumers, outbox for atomic publish, sagas for cross-service flows (Saga Pattern). Anti-pattern: functions calling functions synchronously, which doubles the bill and couples failures. Prefer events and Step Functions for orchestrated flows. Ownership and decisions: Service Communication.
Distributed data: replicas, caches, regions
Functions in several Regions read local replicas or global tables, and a cold function has an empty cache: every cold start is also a cache miss, so a spike of new environments is a spike on the database (a stampede, see Caching). Idempotency stores must be reachable from every Region that can process the same event, or keys must include the Region and you accept duplicates across Regions. Edge functions cannot assume local data.
Scaling path: 1x, 10x, 100x
| Load | Design | What breaks first |
|---|---|---|
| 1x (a few requests per second) | Functions behind API Gateway or function URL, one queue, one table | Nothing; cost is near zero |
| 10x | Queue-fed workers with maximum concurrency, RDS Proxy, provisioned concurrency for hot endpoints, DLQs and alarms | Database connections, cold starts on spikes |
| 100x | Account concurrency increase, SQS provisioned mode, sharded partition keys, move steady paths to containers, multi-Region with idempotency per Region | Account limits, scaling rate (1,000 environments per 10 s), cost per request versus an instance |
Lab: duplicate and partial delivery, with numbers
Experiment 1: run the unit tests with the race detector (run)
cd docs/snippets/system-design/serverless-event-driven-compute/go
go vet ./... && go test -race ./...
# expected: ok for costmodel, idem, sqsbatch (9 handler tests, 3 idempotency tests, 4 cost tests)Experiment 2: partial batch through the local adapter (expected, not run)
go run ./cmd/local &
curl -s localhost:8080/sqs -d '{"Records":[
{"messageId":"m1","body":"{\"id\":\"a\"}","messageAttributes":{"idempotencyKey":{"stringValue":"k1","dataType":"String"}}},
{"messageId":"m2","body":"not json","messageAttributes":{"idempotencyKey":{"stringValue":"k2","dataType":"String"}}}]}'
# expected: {"batchItemFailures":[{"itemIdentifier":"m2"}]}
# send the same body again: m1 is a duplicate (skipped as success), m2 fails againExperiment 3: enable partial responses on a real mapping (expected, not run)
aws lambda update-event-source-mapping --uuid <uuid> \
--function-response-types ReportBatchItemFailures \
--batch-size 10 --scaling-config '{"MaximumConcurrency":5}'
aws sqs send-message-batch ... # 10 messages, 1 invalid
# expected: queue depth returns to 0 except the invalid message; its ApproximateReceiveCount rises
# until maxReceiveCount, then it appears in the DLQExperiment 4: concurrency arithmetic (run on paper)
peak 5,000 rps, 200 ms -> concurrency 1,000 (account default): any growth throttles
the same load at 100 ms -> 500: halving duration halves concurrencyExperiment 5: Laravel redelivery test (expected, not run)
php artisan test --filter=ChargeInvoiceTest
# expected: 3 tests pass; Http::assertSentCount(1) after two dispatches of the same invoiceCommon misconceptions
| Belief | Reality |
|---|---|
| Serverless has no servers | Servers exist; you do not manage them, and you inherit the limits |
| Serverless is always cheaper | Cheaper for idle and spiky load; dearer at steady high utilisation |
| Lambda timeout is 15 minutes | The quotas page read for this chapter says 1,800 s; older sources say 900 s |
| Each invocation is a fresh process | Environments are reused when warm; code outside the handler runs once per environment |
| Cold starts are always a problem | About 0.2 percent of requests on busy PHP apps (Bref); matter for low traffic and tight budgets |
| A function DLQ catches failed SQS messages | For SQS the DLQ is on the queue (redrive policy) |
| Exactly-once processing is built in | Event source mappings are at least once; make handlers idempotent |
| The MessageId is my idempotency key | A producer retry creates a new MessageId; use a business key |
| Scaling to 1,000 is free | Downstream databases and APIs do not scale; cap concurrency |
| Function URL equals API Gateway | A function URL is a simple endpoint with auth AWS_IAM or NONE; API Gateway adds throttling, keys and transformations |
| Edge functions are faster for everything | Not when they call a distant database |
| Containers make it portable | The events, IAM and triggers still tie you to the provider |
Cheat sheet
| Topic | What to remember |
|---|---|
| Definition | Provision nothing, scale to zero, pay per use |
| Invocation | Sync waits; async queues and retries twice; poll reads batches |
| Delivery | At least once everywhere; idempotent handlers |
| Idempotency key | From the business event, with a lease and a retention longer than redelivery |
| Cold start | Init phase; fix with small packages, SnapStart or provisioned concurrency |
| Concurrency | rate x duration; reserve for critical, cap for fragile |
| SQS batch | ReportBatchItemFailures; FIFO stops at first failure |
| Visibility timeout | At least the function timeout, usually several times |
| DLQ | On the queue for SQS; on the function only for async invokes |
| Connections | RDS Proxy or PgBouncer, or cap concurrency |
| Orchestration | Step Functions Standard (exactly-once, year) vs Express (at-least-once, 5 min) |
| Cost | requests x price + GB-seconds x price + hidden lines |
| Limits | 30 min, 6 MB sync, 1 MB async, 10,240 MB, 1,000 concurrency |
| Security | One least-privilege role per function; validate events |
| Observability | X-Ray or OpenTelemetry layer, structured logs, DLQ depth alarms |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — A function handles 300 requests per second with an average duration of 150 ms. What is its concurrency, and what does that mean for a 1,000 account limit? Must-know
Answer
Answer: 300 x 0.15 = 45 concurrent executions, well below 1,000; growth to about 6,600 rps at the same duration would reach the limit.
2 — Why does a handler that throws on one bad SQS message cause good messages to be processed twice? Must-know
Answer
Answer: Without partial batch responses the whole batch is considered failed and becomes visible after the visibility timeout. Enable ReportBatchItemFailures and return the failed ids.
3 — Where do you configure the DLQ for failed SQS-triggered invocations? Important
Answer
Answer: On the source queue's redrive policy with maxReceiveCount; a function DLQ or destination covers asynchronous invokes only.
4 — What should the visibility timeout be relative to the function timeout, and what happens otherwise? Must-know
Answer
Answer: At least the function timeout (plus batch window); otherwise the message reappears while still being processed, creating duplicates.
5 — Name three ways to remove or reduce cold starts on Lambda and a limit of each. Important
Answer
Answer: Smaller package and lighter init (limited gains); SnapStart (selected runtimes, published versions, uniqueness caveats, not with provisioned concurrency); provisioned concurrency (billed while idle).
6 — Why is MessageId a poor idempotency key? Important
Answer
Answer: A producer retry makes a new message with a new id for the same business event; use an order id or request id.
7 — A spike makes the database fail with too many clients. What are your two fixes? Must-know
Answer
Answer: Pool connections (RDS Proxy, PgBouncer) and cap function concurrency (reserved concurrency or SQS maximum concurrency).
8 — When do you choose Step Functions Standard over Express? Important
Answer
Answer: Long-running or non-idempotent steps needing exactly-once execution and history; Express is for high-rate idempotent work up to five minutes.
9 — At what point does serverless become more expensive than an instance? Good to know
Answer
Answer: When steady utilisation is high; compute per-request cost against the instance price: break-even requests equals fixed monthly cost divided by price per request, with duration and memory in the price.
10 — Why can a FIFO queue limit your concurrency? Important
Answer
Answer: Concurrent invocations are capped by the number of message group ids (or maximum concurrency, whichever is lower).
Glossary
| Term | Meaning |
|---|---|
| Serverless | Operating model: no server management, scale to zero, pay per use |
| FaaS (function as a service) | Run one function per event or request, platform handles scaling |
| Scale to zero | No instances while idle, no idle cost |
| Pay per use | Billed by requests and duration, not by reservation |
| Lambda | AWS function platform |
| Invocation | One run of a function |
| Synchronous invocation | Caller waits for the result |
| Asynchronous invocation | Event queued, 202 returned, Lambda retries |
| Event source mapping | Lambda poller that reads queues and streams in batches |
| Poll-based | The platform reads the source and calls the function |
| Execution environment | The sandbox that runs one or more invocations |
| Init phase | Start extensions, runtime and static code |
| Cold start | Extra latency when a new environment is needed |
| Warm start | Reuse of an initialised environment |
| SnapStart | Snapshot of an initialised environment, restored on scale-out |
| Provisioned concurrency | Pre-initialised environments kept ready |
| Reserved concurrency | Per-function maximum and guaranteed share |
| Concurrency limit | Account ceiling of concurrent executions (default 1,000) |
| Timeout | Maximum run time of one invocation |
| Memory | Configured MB; CPU scales with it |
| /tmp | Ephemeral writable storage per environment |
| Layer | Shared package extracted into /opt |
| Container image | Function packaged as an image up to 10 GB |
| Extension | Process that runs next to the function (monitoring, secrets) |
| Cloud Run | Google serverless containers |
| Cloud Functions | Google function product, now Cloud Run functions |
| Azure Functions | Microsoft function platform |
| Cloudflare Workers | V8 isolate-based edge functions |
| Isolate | Lightweight V8 context inside a shared process |
| Vercel | Platform whose routes run as functions |
| Fly Machines | Fast-start VMs on Fly.io |
| API Gateway | Managed HTTP front door for functions |
| Function URL | Built-in HTTPS endpoint for one Lambda function |
| S3 event | Object-created or removed notification |
| EventBridge | Event bus with rules, scheduler, pipes and schema registry |
| EventBridge rule | Pattern that routes events to targets |
| Schema registry | Stored event schemas with generated bindings |
| SNS | Pub/sub topic service |
| SQS | Queue service with visibility timeout |
| Kinesis | Ordered, sharded stream service |
| DynamoDB Streams | Change stream of a DynamoDB table |
| Batch size | Maximum records per invocation |
| Batch window | Maximum time to gather a batch |
| Partial batch response | Report only failed items of a batch |
| ReportBatchItemFailures | Mapping setting that enables partial batch responses |
| DLQ | Dead-letter queue for messages that keep failing |
| Destination | Target for async invocation outcomes |
| Retry | Another attempt after failure |
| Idempotency | Repeating an operation has the same effect as doing it once |
| Stateless | No local state that matters between invocations |
| Connection pooling | Sharing a small set of database connections |
| RDS Proxy | AWS managed database connection pool |
| Step Functions | AWS workflow service with state machines |
| State machine | Defined states and transitions of a workflow |
| Durable Functions | Azure code-first orchestration |
| Choreography | Services react to events without a central conductor |
| Cost per request | Per-invocation price component |
| GB-second | Memory in GB times duration in seconds |
| Egress | Data transferred out of the provider network |
| Payload limit | Maximum request or response size |
| VPC ENI | Network interface Lambda uses to reach a VPC |
| X-Ray | AWS distributed tracing service |
| OTel Lambda layer | OpenTelemetry collector or SDK packaged as a layer |
| SAM | AWS Serverless Application Model |
| LocalStack | Local emulator of AWS services |
| Execution role | IAM role assumed by the function |
| Least privilege | Grant only what is needed |
| Knative | Serverless on Kubernetes (Serving, Eventing) |
| OpenFaaS | Functions on your own cluster |
| Serverless Framework | Deployment tool for functions |
| SST | Infrastructure framework for serverless apps |
| CDK | AWS Cloud Development Kit |
| Lambda@Edge | Lambda functions run at CloudFront edge locations |
| FIFO queue | SQS queue ordered per message group, with deduplication |
| Bref | PHP runtime layer for Lambda |
| Vapor | Laravel serverless deployment platform on Lambda |
| sqs driver | Laravel queue driver for Amazon SQS |
| aws-lambda-go | Go library for Lambda handlers and event types |
References
- Hellerstein et al., Serverless Computing: One Step Forward, Two Steps Back (CIDR 2019): https://arxiv.org/abs/1812.03651
- Jonas et al., Cloud Programming Simplified: A Berkeley View on Serverless Computing: https://www2.eecs.berkeley.edu/Pubs/TechRpts/2019/EECS-2019-3.html
- AWS Lambda execution environment lifecycle: https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtime-environment.html
- Lambda quotas: https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-limits.html
- Lambda scaling and concurrency: https://docs.aws.amazon.com/lambda/latest/dg/lambda-concurrency.html
- Lambda synchronous invocation: https://docs.aws.amazon.com/lambda/latest/dg/invocation-sync.html
- Lambda asynchronous invocation: https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html
- Lambda async error handling: https://docs.aws.amazon.com/lambda/latest/dg/invocation-async-error-handling.html
- Lambda async destinations and DLQ: https://docs.aws.amazon.com/lambda/latest/dg/invocation-async-retain-records.html
- Lambda event source mappings: https://docs.aws.amazon.com/lambda/latest/dg/invocation-eventsourcemapping.html
- Lambda with SQS: https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html
- SQS error handling and partial batch responses: https://docs.aws.amazon.com/lambda/latest/dg/services-sqs-errorhandling.html
- SQS scaling behaviour: https://docs.aws.amazon.com/lambda/latest/dg/services-sqs-scaling.html
- Lambda SnapStart: https://docs.aws.amazon.com/lambda/latest/dg/snapstart.html
- Lambda memory and CPU: https://docs.aws.amazon.com/lambda/latest/dg/configuration-memory.html
- Lambda layers: https://docs.aws.amazon.com/lambda/latest/dg/chapter-layers.html
- Lambda extensions: https://docs.aws.amazon.com/lambda/latest/dg/lambda-extensions.html
- Lambda function URLs: https://docs.aws.amazon.com/lambda/latest/dg/urls-configuration.html
- Lambda in a VPC: https://docs.aws.amazon.com/lambda/latest/dg/configuration-vpc.html
- Lambda with RDS: https://docs.aws.amazon.com/lambda/latest/dg/services-rds.html
- Lambda and X-Ray: https://docs.aws.amazon.com/lambda/latest/dg/services-xray.html
- Lambda Go handler: https://docs.aws.amazon.com/lambda/latest/dg/golang-handler.html
- Lambda pricing: https://aws.amazon.com/lambda/pricing/
- Powertools for AWS Lambda idempotency: https://docs.aws.amazon.com/powertools/python/latest/utilities/idempotency/
- AWS Step Functions: https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html
- Step Functions workflow types: https://docs.aws.amazon.com/step-functions/latest/dg/choosing-workflow-type.html
- Amazon EventBridge: https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html
- EventBridge rules: https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-rules.html
- EventBridge schemas: https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-schema.html
- SNS with SQS: https://docs.aws.amazon.com/sns/latest/dg/sns-sqs-as-subscriber.html
- SQS FIFO delivery logic: https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues-understanding-logic.html
- SQS visibility timeout: https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html
- Google Cloud Run overview: https://cloud.google.com/run/docs/overview/what-is-cloud-run
- Cloud Run concurrency: https://cloud.google.com/run/docs/about-concurrency
- Cloud Run minimum instances: https://cloud.google.com/run/docs/configuring/min-instances
- Cloud Run functions: https://cloud.google.com/functions/docs/concepts/overview
- Cloudflare Workers, how it works: https://developers.cloudflare.com/workers/reference/how-workers-works/
- Cloudflare Workers limits: https://developers.cloudflare.com/workers/platform/limits/
- Vercel Functions limitations: https://vercel.com/docs/functions/limitations
- Fly Machines: https://fly.io/docs/machines/overview/
- Knative Serving: https://knative.dev/docs/serving/
- OpenFaaS: https://docs.openfaas.com/
- Bref: https://bref.sh/
- Bref cold starts: https://bref.sh/docs/environment/cold-starts
- Bref Laravel queues: https://bref.sh/docs/laravel/queues
- Bref Laravel Octane: https://bref.sh/docs/laravel/octane
- Bref cron tasks: https://bref.sh/docs/use-cases/cron
- Laravel Vapor: https://docs.vapor.build/
- Vapor queues: https://docs.vapor.build/resources/queues
- Laravel 13 queues: https://laravel.com/docs/13.x/queues
- Laravel 13 scheduling: https://laravel.com/docs/13.x/scheduling
- Laravel 13 Octane: https://laravel.com/docs/13.x/octane
- aws-lambda-go: https://pkg.go.dev/github.com/aws/aws-lambda-go/lambda
- aws-lambda-go events: https://pkg.go.dev/github.com/aws/aws-lambda-go/events