Skip to content

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 forGo to
The whole page in five tablesEverything in one minute
What "serverless" promises and costsWhy it exists
Papers and product historyWhere it comes from
FaaS vs serverless containers vs managed servicesDefinitions
Sync, async and poll-based invocationInvocation types
Init, Invoke, freeze, reuseExecution environment
Cold starts, SnapStart, provisioned concurrencyCold starts
Reserved concurrency, limits, throttlingConcurrency
SQS, Kinesis, S3, EventBridge, SNS, cronEvent sources
Batch size, batch window, ReportBatchItemFailuresBatches and partial failure
DLQ, destinations, retriesRetries and DLQs
Idempotent handlersIdempotency
State, connection pooling, RDS ProxyStateless by force
Step Functions, Durable Functions, choreographyOrchestration
Cloud Run, Azure, Workers, Vercel, FlyOther platforms
Edge functionsEdge
Price per request and per GB-secondCost model
VPC, payload, observability, testingGotchas
Roles, secrets, event injectionSecurity
Knative, OpenFaaS, SST, CDKPortability
Fan-out, ordering, backpressureEvent-driven design
Exact limits and error namesMechanics
CodeGo, Laravel
Classic failuresSolving the classic problems
Which compute for which workloadChoosing
Monolith to distributed systemIn architecture
Numbers and commandsLab
Beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The three families of "serverless".

FamilyYou shipUnit of scalingScale to zeroTypical products
FaaS (function as a service)A function and its dependenciesOne execution environment per concurrent request (Lambda)YesAWS Lambda, Azure Functions, Cloud Run functions, Cloudflare Workers, Vercel Functions, Netlify Functions
Serverless containersA container image that listens on a portAn instance that serves many concurrent requestsYes (configurable)Google Cloud Run, Knative Serving, Azure Container Apps, AWS Fargate (not scale-to-zero by itself)
Managed services ("serverless" data and glue)ConfigurationHiddenMostly (billed per use)Amazon SQS, SNS, EventBridge, DynamoDB, S3, Step Functions

Lambda invocation styles.

StyleWho waitsRetriesTypical sources
Synchronous (RequestResponse)The caller gets the result or the errorThe caller must retryAPI Gateway, ALB, function URL, SDK Invoke
Asynchronous (Event)Nobody; Lambda queues the event and returns 202Lambda retries twice by default; DLQ or destination for the failuresS3, SNS, EventBridge, SDK with Event
Poll-based (event source mapping)Lambda pollers read and invoke the function synchronously with a batchDepends on the source: SQS message returns after the visibility timeout, streams retry the batchSQS, Kinesis, DynamoDB Streams, MSK and self-managed Kafka, Amazon MQ

Numbers worth remembering (Lambda, from the AWS quotas page read for this chapter).

NumberMeaning
1,800 sFunction timeout: 30 minutes (older documentation and many tutorials say 900 s, 15 minutes)
128 to 10,240 MBMemory; CPU is proportional; 1,769 MB is one vCPU
6 MB / 1 MBRequest and response payload for synchronous / asynchronous invocation
1,000Default account concurrency per Region (soft limit)
1,000 per 10 sPer-function scale-out rate: new execution environments
10 sInit phase limit for on-demand functions (not with SnapStart or provisioned concurrency)
512 to 10,240 MB/tmp size
5 layers, 250 MB unzippedLayers and unzipped package size; container images up to 10 GB

The five rules the rest of the page unpacks.

RuleWhy
Assume every event arrives twiceEvent source mappings and asynchronous invokes are at least once
Keep nothing important in the functionEnvironments are created, frozen and destroyed at the provider's will
Put a queue between a spike and anything fragileConcurrency limits and a queue turn a burst into a steady stream
Cap concurrency downstream of the functionLambda scales faster than your database
Do the arithmetic before you chooseCost is requests times duration times memory, not "cheap"
Init (cold)Invoke #1frozenInvoke #2frozenInvoke #3Shutdownbilled on first usewarm: no Initidle too longtimeInit phase (limit 10 s on demand)1 extensions start 2 runtime bootstraps3 your static code runs: clients, config, poolsInvoke phase (limit = function timeout)handler runs; memory and /tmp survivebetween invokes, but never rely on them

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 getWhat you pay
No servers to patch or sizeA fixed execution model: time, memory, payload and concurrency limits
Scale to zero: no idle billCold starts: the first request after idle pays Init
Fast scale-out without a capacity planScale-out can overwhelm databases and third-party APIs
Pay per request and per millisecondAbove a steady utilisation threshold it costs more than an instance
Built-in integration with queues, streams, schedulesLock-in to the provider's event shapes and IAM
Isolation per invocationNo 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 ​

  1. "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).
  2. "Serverless is always cheaper." It is cheaper for idle and spiky load and more expensive for steady high utilisation. See the cost model.
  3. "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.

QuestionFaaS (Lambda)Serverless container (Cloud Run)Always-on container
Concurrent requests per instanceOne (default)Many (default 80 per vCPU through the CLI, up to 1,000)Many
Scale to zeroYesYes unless minimum instances setNo
PackagingZip or image with a handlerAny container listening on a portAny container
Max request time30 minutes (Lambda quotas page)Configurable request timeoutUnbounded
Billing granularityPer request plus GB-secondCPU 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 failures

Real 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.

PropertySynchronousAsynchronousEvent source mapping
Payload limit6 MB request and response1 MBBatch size and 6 MB invoke payload
Retry ownerCallerLambda: 2 more attempts, 1 and 2 minute waits; throttling retried up to 6 hoursThe source (SQS visibility timeout; stream retries)
Failure captureError in responseDLQ (SQS or SNS standard) or on-failure destinationSQS redrive DLQ; stream on-failure destination
Delivery semanticsExactly what the caller doesAt least onceAt least once
OrderingNot applicableNot guaranteedPer 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 destroyed

Real 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.

BehaviourGuaranteed?
Code outside the handler runs once per new environmentYes
The same environment serves many sequential invocationsNo guarantee; common under steady traffic
/tmp survives between invocationsOnly in a warm environment; never rely on it
Two concurrent requests share an environmentNo; each concurrent request needs its own (Lambda default)
Background work continues after the handler returnsIt is frozen; do not rely on it
Time between invocations is billedNo

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.

MitigationWhat it removesLimits and cost
Smaller package, lazy initDownload and Init timeFree
Language choiceGo 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
SnapStartInit 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 concurrencyCold starts for N environmentsYou pay for the idle environments; Init may run up to 15 minutes
Warmers (scheduled pings)Cold starts for one environment per pingBref documents this for low traffic: a schedule event every 5 minutes
Cloud Run minimum instancesScale-to-zero cold startsIdle 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 invocations

Real 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.

ControlWhat it doesCost
Account limit (1,000 default)Hard ceiling for all functions in a RegionSoft: request an increase
Reserved concurrencyMaximum and guaranteed minimum for one functionFree; counts against the account
Provisioned concurrencyPre-initialised environments, up to a number you setBilled while provisioned
SQS maximum concurrencyPer event source capFree
SQS provisioned modeDedicated pollers, faster scaling (up to 1,000 invokes per minute added)Extra cost
Function scaling limit1,000 environments per 10 s per functionHard

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) -> function

Real 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.

SourceInvocation typeOrderingFailure handling
API Gateway, ALB, function URLSyncNoneCaller sees 5xx and retries; function URLs have auth AWS_IAM or NONE
S3, SNS, EventBridgeAsyncNoneLambda retries, DLQ or destination
SQS standardPollBest effortVisibility timeout, redrive DLQ, ReportBatchItemFailures
SQS FIFOPollPer message groupStop at first failure in a group
Kinesis, DynamoDB StreamsPollPer shardA failing batch blocks the shard until it succeeds, expires or a bisect/destination setting moves on
EventBridge SchedulerAsyncNot applicableConfigurable retries and DLQ
MSK / KafkaPollPer partitionBatch 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 receive

Real 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.

SettingMeaningValue
BatchSizeRecords per invocationDefault 10 on SQS; larger batches (up to 10,000) need a batch window
MaximumBatchingWindowInSecondsGather time0 to 300 s; FIFO needs provisioned mode for a window
ScalingConfig.MaximumConcurrencyCap on concurrent invokes from one SQS source2 to 1,000
FunctionResponseTypesReportBatchItemFailuresPer mapping
FIFO ruleStop at first failure, return it and everything after itKeeps order inside a group
Poller scaling (standard queue)Starts at 5 concurrent invokes, adds up to 300 per minute, max 1,250 per mappingProvisioned 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 DLQ

Real 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.

MechanismApplies toCapturesNotes
SQS redrive DLQ + maxReceiveCountSQS event sourceThe original messageConfigure on the queue; give it long retention
Function DLQAsync invokesThe event onlySQS or SNS standard
On-failure destinationAsync invokesEvent, error, attempt countPreferred over DLQ for richer data
Stream on-failure destinationKinesis, DynamoDB, Kafka mappingsMetadata of the failed batchNot the records themselves
Maximum retry attempts / event ageAsync and stream mappingsLimits the retriesSet 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 Claimed

Real 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.

StoreAtomic claimNotes
DynamoDBPutItem with attribute_not_exists(pk) and a TTL attributeThe Powertools default
PostgreSQL / MySQLINSERT ... ON CONFLICT DO NOTHING / INSERT IGNORE, row count tells who wonSame transaction as the business write gives atomicity
RedisSET key value NX PX leaseFast; lease only, durability depends on config
In-memory mapPer environment onlyTests and local adapter only
sql
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 database

Real 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.

OptionHelps withCosts
RDS ProxyConnection count, failover pinningHourly charge based on database size
PgBouncer in transaction modeConnection countYou run it; prepared statements and session state limits
RDS Data APINo connections at allHTTP latency, payload limits
Reserved concurrency / SQS max concurrencyLimits parallelismLower throughput
DynamoDB or other HTTP-based storesNo pooling issueDifferent data model
Redis for sessions and locksShared stateAnother 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 -> email

Real 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.

OptionStrengthWeakness
Step Functions StandardVisible history, exactly-once, long runningPriced by state transition
Step Functions ExpressHigh rate, priced by durationAt-least-once, five minutes
Azure Durable FunctionsOrchestrator codeDeterministic-code constraints
TemporalPortable, rich semanticsYou run or buy it
EventBridge rules (choreography)Loose couplingFlow is implicit; debugging needs tracing
One function calling another synchronouslySimpleDouble 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):

PlatformModelLimits worth knowing
AWS LambdaOne request per environment, microVM30 minute timeout, 6 MB sync payload, 10 GB image
Google Cloud Run (services, functions, jobs)Container; many requests per instanceConcurrency per instance default 80 times vCPUs (CLI), up to 1,000; scale to zero or minimum instances; billed per 100 ms
Azure FunctionsFunctions on Consumption, Flex Consumption or Premium plansNot fetched for this chapter (the Microsoft pages were unreachable); check the hosting plan documentation
Cloudflare WorkersV8 isolates in a shared runtime128 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 FunctionsFunctions behind a deploymentDefault duration 300 s; Pro maximum 800 s; request body 4.5 MB by default; timeout returns 504 FUNCTION_INVOCATION_TIMEOUT
Netlify FunctionsFunctions on AWS Lambda behind NetlifyNot fetched; check the limits page
Fly MachinesFast-booting VMs with a REST APIStart usually "well under a second"; you stop and start Machines yourself or let the proxy do it
Knative ServingKubernetes service with request-based autoscalingScale 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 instance

Real 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 region

Real scenario: rewrite / to a localised path from the Accept-Language header at the edge; verify a JWT signature before forwarding.

ConcernEdge functionRegional function
Latency to userLowestRegion distance
Access to a regional databaseSlow or replicatedFast
CPU and memory budgetSmallLarge
LibrariesRestricted APIsFull 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 less

Real 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.

FactorPushes toward serverlessPushes toward containers
UtilisationUnder about 10 to 20 percent averageAbove about 40 percent steady (inference, depends on prices)
Traffic shapeSpiky, bursty, event drivenFlat
Duration per requestShortLong (duration is the bill)
Memory per requestSmallLarge
Egress and NATSmall payloadsLarge; costs the same either way, plus NAT for VPC functions
Operations staffSmall teamPlatform team available
Hidden linesAPI Gateway, logs, NATIdle 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:

GotchaWhat happensMitigation
Payload limitSync 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 MBPass references (S3 key), not blobs; presigned URLs
TimeoutFunction killed at the timeout; SQS visibility timeout shorter than the function means the message is delivered again while it runsSet visibility timeout above the function timeout; keep work chunked
VPC attachmentFunctions in a VPC use Hyperplane ENIs, lose internet access unless the VPC has NAT or endpoints; ENI quota 3,000 per VPCUse VPC endpoints, plan subnets, attach only when needed
Network egressBilled; NAT gateways charge per hour and per GBGateway endpoints for S3 and DynamoDB
Throttling429 when concurrency is exhausted; async retried for up to 6 hoursReserved concurrency, queues
LogsEvery print costs money and latencyStructured, sampled logs
Clock and timeHandler returns while background goroutines freezeWait for work before returning
Deployment size50 MB zipped, 250 MB unzippedLayers, 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 -> safe

Real scenario: a single shared admin role on twenty functions turns a bug in one into a breach of all; per-function roles confine it.

ControlPractice
Execution roleOne per function; deny by default; scope to ARNs and prefixes
Resource policyOnly the services and accounts that should invoke
SecretsSecrets Manager, cached; rotate; never in logs
InputValidate, parameterise, size-limit
DependenciesPin and scan; layers are code too
NetworkVPC 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, Publisher

Real 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.

LayerPortability
Domain codeHigh
Handler signature and event typesProvider specific (aws-lambda-go events)
IAM and triggersProvider specific
IaC (CDK, SAM, SST, Serverless Framework)Tool and provider specific
Knative, OpenFaaSPortable 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 lost

Real scenario: Black Friday traffic: the API stays fast because it only writes and publishes; the billing consumer drains at a controlled rate.

API Gateway+ functionSNS topicor EventBridge busqueue: emailqueue: billingqueue: searchLambda emailLambda billingLambda searchSESdatabaseDLQ per queuemax concurrency = 20queues absorb the burst; each consumer scales and fails on its own
NeedToolDetail
Fan-outSNS to SQS to LambdaOne queue per consumer
Routing by contentEventBridge rulesPatterns on event fields
Strict order per entitySQS FIFO with MessageGroupId, or Kinesis partition keyConcurrency limited by number of groups or shards
BufferingSQSVisible depth and age
Throttling downstreamMaximum concurrency, reserved concurrencyDrain at a safe rate
ReplayKinesis retention, EventBridge archive, DLQ redrivePlan 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.

SQS queuevisibility timeoutat least onceEvent sourcemappingpollers, batch size,batch windowLambda functionper message: claim key,work, completesucceededdeleted from queuebatchItemFailuresReportBatchItemFailuresDLQafter maxReceiveCountfailed ids reappear after the visibility timeout (retry)partial response: only failed ids go back

Mechanics ​

Knobs and where they live ​

KnobWhereDefaultNotes
Function timeoutFunction configuration3 s when created from the console (general knowledge)Max 1,800 s
MemoryFunction configuration128 MBCPU scales with it
Ephemeral storage /tmpFunction configuration512 MBUp to 10,240 MB
ReservedConcurrentExecutionsFunctionNoneBoth a cap and a reservation
Provisioned concurrencyAlias or version0Billed
BatchSizeEvent source mappingSQS 10Window needed above 10
MaximumBatchingWindowInSecondsEvent source mapping0 for SQSUp to 300
FunctionResponseTypesEvent source mappingEmptyReportBatchItemFailures
ScalingConfig.MaximumConcurrencySQS mappingNone2 to 1,000
SQS visibility timeoutQueue30 sSet above the function timeout
maxReceiveCountQueue redrive policyNoneMoves to the DLQ
Async MaximumRetryAttempts, MaximumEventAgeInSecondsFunction event invoke config2 retries, 6 hoursLower to fail fast

Error names and codes you will see ​

ErrorMeaningWhat to do
HTTP 429 TooManyRequestsExceptionConcurrency or rate exhaustedReserved concurrency, queue, backoff
HTTP 502 from API GatewayMalformed function response or crashReturn the documented shape; check logs
HTTP 504 (API Gateway, Vercel FUNCTION_INVOCATION_TIMEOUT)Integration or function timeoutShorten work, async pattern
Task timed out after N secondsFunction timeoutRaise timeout or chunk work
INIT_REPORT ... Status: timeoutInit exceeded 10 sLighter init, SnapStart, provisioned concurrency
SnapStartTimeoutExceptionRestore exceeded its limitShorten after-restore hooks
Runtime.ExitErrorProcess exited unexpectedlyCheck panics, OOM
Out of memory (Max Memory Used equals memory size)Memory exhaustionRaise memory
DestinationDeliveryFailures metricLambda could not write to the destinationFix permissions or use a standard queue
Cloudflare Error 1102 Worker exceeded resource limitsCPU or memory limitStream bodies, raise CPU limit on Paid
FATAL: sorry, too many clients already (PostgreSQL)Connection exhaustionPool 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 larger

Go ​

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.

go
// 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.

go
// 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
}
go
// 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)
}
go
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
}
go
// 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.

go
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")
	}
}
go
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:

go
// 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())
}
go
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:

go
// 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
}
go
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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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:

yml
# 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
yml
# 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 sqs driver needs aws/aws-sdk-php; there is no retry_after for SQS: the queue's default visibility timeout decides redelivery (Laravel queue documentation). Set after_commit so 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 $tries are attempted 3 times (not once as queue:work does), failed jobs go to failed_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() or messageGroup() 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-concurrency and per-queue limits (- invoices: 10) cap Lambda concurrency; warm: 5 prewarms 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:run every minute (Bref's cron page); onOneServer() is not needed because one place invokes it, but use withoutOverlapping() 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 OctaneHandler with BREF_LOOP_MAX restarts 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 (set idle_in_transaction_session_timeout on 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 ​

SolutionHowAdvantageCost or limit
Queue between API and workerAPI writes to SQS; worker function drainsBuffer and visible backlogEventual completion
SQS maximum concurrency / reserved concurrencyCap drain ratePredictable loadLower throughput
RDS Proxy or PgBouncerPool connectionsMany functions, few connectionsExtra 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 ​

WorkloadRecommendationExtra techniqueReason
Webhook receiver, low volumeFunctionQueue behind itNo idle cost, spikes absorbed
Event glue between managed servicesFunctionEventBridge or SQSNative integration
Spiky public API with relaxed latencyFunction + API Gateway or function URLProvisioned concurrency for hot pathsScale to zero
Steady API, 40 percent or more utilisationContainers or serverless containersAutoscalingLower cost per request
Long jobs over 30 minutesContainers, batch jobs, Step FunctionsChunkingFunction limits
Connection-heavy database accessContainers, or functions + RDS ProxyConcurrency capPool pressure
Strict p99 under about 100 msContainers, or provisioned concurrencyEdge cacheCold starts
Edge personalisation, redirectsEdge functionsKVLatency
Orchestrated multi-step business flowStep Functions or TemporalIdempotent stepsVisibility, compensation
Portable, Kubernetes shopKnative or OpenFaaSCloudEventsAvoid lock-in
Spiky or mostly idle?peak / average above ~10Work per request short?under minutes, stateless, fits limitsTail latency and connections?p99 budget, DB pool, socketsFunctions (FaaS)pay per use, scale to zeroServerless containersCloud Run, Fargate, KnativeContainers or instancessteady load, pooled connectionsAnswer yes, yes, no: functions. Mixed answers: containers that scale to zero. The ratio and the limits decide, not fashion.

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 ​

LoadDesignWhat breaks first
1x (a few requests per second)Functions behind API Gateway or function URL, one queue, one tableNothing; cost is near zero
10xQueue-fed workers with maximum concurrency, RDS Proxy, provisioned concurrency for hot endpoints, DLQs and alarmsDatabase connections, cold starts on spikes
100xAccount concurrency increase, SQS provisioned mode, sharded partition keys, move steady paths to containers, multi-Region with idempotency per RegionAccount 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 again

Experiment 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 DLQ

Experiment 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 concurrency

Experiment 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 invoice

Common misconceptions ​

BeliefReality
Serverless has no serversServers exist; you do not manage them, and you inherit the limits
Serverless is always cheaperCheaper for idle and spiky load; dearer at steady high utilisation
Lambda timeout is 15 minutesThe quotas page read for this chapter says 1,800 s; older sources say 900 s
Each invocation is a fresh processEnvironments are reused when warm; code outside the handler runs once per environment
Cold starts are always a problemAbout 0.2 percent of requests on busy PHP apps (Bref); matter for low traffic and tight budgets
A function DLQ catches failed SQS messagesFor SQS the DLQ is on the queue (redrive policy)
Exactly-once processing is built inEvent source mappings are at least once; make handlers idempotent
The MessageId is my idempotency keyA producer retry creates a new MessageId; use a business key
Scaling to 1,000 is freeDownstream databases and APIs do not scale; cap concurrency
Function URL equals API GatewayA function URL is a simple endpoint with auth AWS_IAM or NONE; API Gateway adds throttling, keys and transformations
Edge functions are faster for everythingNot when they call a distant database
Containers make it portableThe events, IAM and triggers still tie you to the provider

Cheat sheet ​

TopicWhat to remember
DefinitionProvision nothing, scale to zero, pay per use
InvocationSync waits; async queues and retries twice; poll reads batches
DeliveryAt least once everywhere; idempotent handlers
Idempotency keyFrom the business event, with a lease and a retention longer than redelivery
Cold startInit phase; fix with small packages, SnapStart or provisioned concurrency
Concurrencyrate x duration; reserve for critical, cap for fragile
SQS batchReportBatchItemFailures; FIFO stops at first failure
Visibility timeoutAt least the function timeout, usually several times
DLQOn the queue for SQS; on the function only for async invokes
ConnectionsRDS Proxy or PgBouncer, or cap concurrency
OrchestrationStep Functions Standard (exactly-once, year) vs Express (at-least-once, 5 min)
Costrequests x price + GB-seconds x price + hidden lines
Limits30 min, 6 MB sync, 1 MB async, 10,240 MB, 1,000 concurrency
SecurityOne least-privilege role per function; validate events
ObservabilityX-Ray or OpenTelemetry layer, structured logs, DLQ depth alarms

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
ServerlessOperating 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 zeroNo instances while idle, no idle cost
Pay per useBilled by requests and duration, not by reservation
LambdaAWS function platform
InvocationOne run of a function
Synchronous invocationCaller waits for the result
Asynchronous invocationEvent queued, 202 returned, Lambda retries
Event source mappingLambda poller that reads queues and streams in batches
Poll-basedThe platform reads the source and calls the function
Execution environmentThe sandbox that runs one or more invocations
Init phaseStart extensions, runtime and static code
Cold startExtra latency when a new environment is needed
Warm startReuse of an initialised environment
SnapStartSnapshot of an initialised environment, restored on scale-out
Provisioned concurrencyPre-initialised environments kept ready
Reserved concurrencyPer-function maximum and guaranteed share
Concurrency limitAccount ceiling of concurrent executions (default 1,000)
TimeoutMaximum run time of one invocation
MemoryConfigured MB; CPU scales with it
/tmpEphemeral writable storage per environment
LayerShared package extracted into /opt
Container imageFunction packaged as an image up to 10 GB
ExtensionProcess that runs next to the function (monitoring, secrets)
Cloud RunGoogle serverless containers
Cloud FunctionsGoogle function product, now Cloud Run functions
Azure FunctionsMicrosoft function platform
Cloudflare WorkersV8 isolate-based edge functions
IsolateLightweight V8 context inside a shared process
VercelPlatform whose routes run as functions
Fly MachinesFast-start VMs on Fly.io
API GatewayManaged HTTP front door for functions
Function URLBuilt-in HTTPS endpoint for one Lambda function
S3 eventObject-created or removed notification
EventBridgeEvent bus with rules, scheduler, pipes and schema registry
EventBridge rulePattern that routes events to targets
Schema registryStored event schemas with generated bindings
SNSPub/sub topic service
SQSQueue service with visibility timeout
KinesisOrdered, sharded stream service
DynamoDB StreamsChange stream of a DynamoDB table
Batch sizeMaximum records per invocation
Batch windowMaximum time to gather a batch
Partial batch responseReport only failed items of a batch
ReportBatchItemFailuresMapping setting that enables partial batch responses
DLQDead-letter queue for messages that keep failing
DestinationTarget for async invocation outcomes
RetryAnother attempt after failure
IdempotencyRepeating an operation has the same effect as doing it once
StatelessNo local state that matters between invocations
Connection poolingSharing a small set of database connections
RDS ProxyAWS managed database connection pool
Step FunctionsAWS workflow service with state machines
State machineDefined states and transitions of a workflow
Durable FunctionsAzure code-first orchestration
ChoreographyServices react to events without a central conductor
Cost per requestPer-invocation price component
GB-secondMemory in GB times duration in seconds
EgressData transferred out of the provider network
Payload limitMaximum request or response size
VPC ENINetwork interface Lambda uses to reach a VPC
X-RayAWS distributed tracing service
OTel Lambda layerOpenTelemetry collector or SDK packaged as a layer
SAMAWS Serverless Application Model
LocalStackLocal emulator of AWS services
Execution roleIAM role assumed by the function
Least privilegeGrant only what is needed
KnativeServerless on Kubernetes (Serving, Eventing)
OpenFaaSFunctions on your own cluster
Serverless FrameworkDeployment tool for functions
SSTInfrastructure framework for serverless apps
CDKAWS Cloud Development Kit
Lambda@EdgeLambda functions run at CloudFront edge locations
FIFO queueSQS queue ordered per message group, with deduplication
BrefPHP runtime layer for Lambda
VaporLaravel serverless deployment platform on Lambda
sqs driverLaravel queue driver for Amazon SQS
aws-lambda-goGo library for Lambda handlers and event types

References ​

Built by Morteza Negahi