Lambda
Real code execution in Docker containers across 31 runtimes. Event source mappings, warm container reuse.
fakecloud implements 88 of 88 Lambda operations at 100% Smithy conformance. Unlike most emulators, Lambda functions actually execute — fakecloud runs your code inside real Docker containers.
Supported features
- Function CRUD — create, update, delete, list, get
- Tagging: functions, event source mappings, code signing configs and capacity providers take
Tagson create andTagResource/UntagResource/ListTagson their ARN. Tags follow Lambda's rules on every path, CloudFormation included: keys of 1 to 128 and values of up to 256 characters from the model's character set (ValidationException), no keys in the reservedaws:namespace and at most 50 tags per resource, counting the ones it already has (InvalidParameterValueException). Under--iam strictthe tagging operations are authorized against the tagged resource's ARN, and a create that carriesTagsalso needslambda:TagResourceon the new resource - Real code execution — functions run in Docker containers with the official AWS Lambda runtime images
- Errors shaped like Lambda's: the error code travels in the
x-amzn-ErrorTypeheader and the JSON body carries the error shape's own members, as recorded on AWS:{"Type":"User","Message":"Function not found: ..."}forResourceNotFoundException,{"Type":"User","message":"..."}for errors whose model names the membermessage(InvalidParameterValueException,ResourceConflictException, ...),{"Message":"..."}with noTypefor the KMS errors of durable functions (KMSDisabledException,KMSInvalidStateException) and forAccessDeniedException,"Type":nullwhere AWS sends it (DurableExecutionAlreadyStartedException, an undecodable callback id), and just{"message":"..."}for other errors outside Lambda's model (ValidationException) - Regional, like AWS: functions, versions, aliases, function URL configs, concurrency settings (and the account concurrency limit), event source mappings, layers, code signing configs and account settings live in one region. The same function name can exist in several regions with different code and configuration,
ListFunctionsreturns the request region's functions only, and a function ARN from another region is refused withResourceNotFoundException: Functions from '<region>' are not reachable in this region ('<region>'). AnInvokeby ARN or partial ARN reaches the account the ARN names; cross-service triggers (SNS, SQS/Kinesis/DynamoDB Streams pollers, EventBridge, Step Functions, API Gateway, S3, Cognito, CloudFormation) resolve the function in the region and account of its ARN - 31 runtimes — Node.js (16/18/20/22/24/26), Python (3.8 through 3.15), Java (
java8.al2,java8.al2023, 11,java11.al2023, 17,java17.al2023, 21, 25), Go (1.x), Ruby (3.2/3.3/3.4/4.0), .NET (8/10),provided.al2,provided.al2023. Node.js 26 and Python 3.15 run on AWS's-previewbase images, the only ones published for them so far - Event source mappings — SQS, Kinesis, DynamoDB Streams polling loops with
FilterCriteria(the same pattern matcher as EventBridge rules, with SQS JSON body decode and base64 Kinesisdatadecode),StartingPosition(TRIM_HORIZON/LATEST/AT_TIMESTAMPfor Kinesis,TRIM_HORIZON/LATESTfor DDB Streams),MaximumBatchingWindowInSeconds(SQS; a partial batch held for the window stays visible in the queue), andFunctionResponseTypes=[ReportBatchItemFailures]partial-batch failure semantics (SQS, Kinesis, DynamoDB Streams). An SQS mapping hands several batches to the function at once, at mostScalingConfig.MaximumConcurrencyof them (five without it, the concurrency AWS starts an SQS mapping at; AWS's further scale-up under a sustained backlog is not modelled); the other messages stay in the queue until a batch finishes, and a FIFO message group is never in two batches at once, so its order holds. The mapping receives exactly asReceiveMessagedoes and shares the queue's in-flight set with API consumers: a received message is in flight with a receipt handle and a counted receive (ApproximateReceiveCount), a FIFO group with a message in flight (received by either) hands out nothing else, and the receive pastmaxReceiveCountmoves a message to the dead-letter queue. A message the mapping still has with the function is never received again by it, even with aVisibilityTimeoutof 0. Kinesis and DynamoDB Streams mappings retry a failed batch with exponential backoff up toMaximumRetryAttempts(default-1, until the records expire), drop batches older thanMaximumRecordAgeInSeconds, split a failing batch withBisectBatchOnFunctionError, and send a discarded batch'sKinesisBatchInfo/DDBStreamBatchInforecord to theOnFailuredestination (SQS, SNS, or S3 with the batch's event aspayload), as recorded on AWS; a batch Lambda cannot run at all is retried without using up retries.CreateEventSourceMappingrefuses a queue or stream that does not exist, a source in another region, and an unsupported source service, with AWS's own errors - Kafka event source mappings: Amazon MSK mappings (
EventSourceArna cluster ARN, read through the cluster's real broker container) and self-managed Apache Kafka mappings (SelfManagedEventSource.Endpoints.KAFKA_BOOTSTRAP_SERVERS) are polled by a real Kafka consumer in the group named byConsumerGroupId(the mapping's UUID by default). AConsumerGroupIdmust be unique among the region's Kafka mappings: creating a second mapping (API or CloudFormation) in a group another mapping uses isResourceConflictException, and the consumer never commits an offset below what the group has already committed. Records are read with theread_committedisolation level: records of aborted transactions are never delivered and those of open transactions wait for their commit (AWS does not document the level its poller uses). A partition without a leader is skipped until one is elected, and a partition whose records cannot be read (the legacy pre-0.11 message format, a corrupt batch) is reported inLastProcessingResultand skipped while the other partitions keep being delivered. A partition the group has no committed offset for starts atStartingPosition(TRIM_HORIZON,LATEST, orAT_TIMESTAMPwithStartingPositionTimestamp), and that position is committed as the mapping starts. Records are batched up toBatchSize(default 100), the 6 MB invocation payload limit orMaximumBatchingWindowInSeconds(500 ms by default) and delivered as Lambda's Kafka event:eventSourceaws:kafkawitheventSourceArn, orSelfManagedKafka,bootstrapServers, andrecordskeyed<topic>-<partition>withtopic,partition,offset,timestamp,timestampType, base64key/value(left out when null) andheadersas byte arrays.FilterCriteriapatterns seevaluedecoded (as JSON when it is JSON); records they drop are committed without an invocation. Offsets are committed to the broker only after the batch succeeded, so a restart, a disabled-then-enabled mapping or a new mapping in the same group resumes after the last handled record. A failing batch is retried whole until it succeeds or its records expire;MaximumRetryAttempts(capped at 10 when an OnFailure destination is set without one),MaximumRecordAgeInSeconds,BisectBatchOnFunctionErrorand the SQS / SNS / S3 OnFailure destination (aKafkaBatchInforecord) apply as for streams, andReportBatchItemFailuresresponses are not interpreted (a batch succeeds or fails whole).LastProcessingResultreportsOK,PROBLEM: Function call failed, or the connection, topic or authentication problem the poller hit. Self-managed brokers are reached over PLAINTEXT, or SASL_PLAINTEXT withBASIC_AUTH(SASL/PLAIN),SASL_SCRAM_256_AUTHorSASL_SCRAM_512_AUTHcredentials read from the Secrets Manager secret ({"username","password"});CLIENT_CERTIFICATE_TLS_AUTH,SERVER_ROOT_CA_CERTIFICATEand OAUTHBEARER are refused inLastProcessingResult. An MSK cluster's broker serves every client on its PLAINTEXT listener, so an MSK mapping'sSASL_SCRAM_512_AUTH/CLIENT_CERTIFICATE_TLS_AUTHsettings are checked against the cluster (the scheme enabled, the SCRAM secret associated with the cluster and readable) rather than negotiated. TheQueueconsumption mode andSchemaRegistryConfigare refused inLastProcessingResult. An MSK cluster without a running broker (no container runtime, serverless) reports a connection problem - Amazon MQ mappings consume the broker's real engine container (the broker data plane, so the broker must be
RUNNINGwith a container runtime available): ActiveMQ over STOMP, RabbitMQ over AMQP 0-9-1, reading the one queue inQueues(RabbitMQ: in the virtual host of theVIRTUAL_HOSTsource access configuration,/by default) as theusername/passwordof theBASIC_AUTHSecrets Manager secret. Messages are batched up toBatchSize(default 100), for at mostMaximumBatchingWindowInSecondsafter the first (default 500 ms) and under the 6 MB payload limit, and the function gets AWS's event:aws:mqwithmessages[](messageID,messageType,timestamp,deliveryMode,correlationID,replyTo,destination.physicalName,redelivered,type,expiration,priority, base64data,brokerInTime,brokerOutTime,properties) for ActiveMQ,aws:rmqwithrmqMessagesByQueuekeyed<queue>::<virtual host>(basicProperties,redelivered, base64data) for RabbitMQ. A batch is acknowledged on the broker only after the invocation succeeds; one the function fails is redelivered by the broker (RabbitMQ: rejected with requeue; ActiveMQ: the consumer session is dropped so the broker returns its unacknowledged messages), marked redelivered, and is retried until it succeeds or a broker-side dead-letter policy takes it.FilterCriteriaapplies to the message with itsdatadecoded when it is JSON, and messages it drops are acknowledged without invoking. A message too large to fit the 6 MB payload even on its own is never delivered: it stays on the broker unacknowledged and the mapping reportsPROBLEM: A message exceeds Lambda's 6 MB invocation payload limit and cannot be delivered., retrying with a backoff that doubles up to a minute while the same problem repeats (the same backoff applies to a broker that stays unreachable).LastProcessingResultreportsOK,PROBLEM: Function call failed.or the connection / authentication / secret / message-size problem of the last attempt. Unacknowledged messages stay on the broker, so a restart resumes where the mapping left off. ActiveMQ'sbrokerInTimeis the message's broker timestamp, since STOMP does not carry the separate broker arrival time. - DocumentDB mappings are stored and returned with their configuration but never polled: fakecloud's DocumentDB is a control plane only, with no MongoDB-compatible engine behind its clusters, so there are no change streams to read.
- Per-source mapping settings:
BatchSizedefaults to 10 for SQS and 100 for every other source. A Kafka mapping always carries itsAmazonManagedKafkaEventSourceConfig/SelfManagedKafkaEventSourceConfig, withConsumerGroupIddefaulting to the mapping's UUID andSchemaRegistryConfig(URI,EventRecordFormat,AccessConfigs,SchemaValidationConfigs) checked against the model.ConsumerGroupId(and a self-managed mapping'sConsumptionMode) cannot be changed byUpdateEventSourceMapping, while the schema registry can.ScalingConfig(SQS),ProvisionedPollerConfig(SQS and Kafka, with the documentedMinimumPollers/MaximumPollersdefaults and per-source bounds) andLoggingConfig(Kafka) are refused on sources that do not take them, and an empty one on update removes the setting.EventSourceMappingArnisarn:aws:lambda:<region>:<account>:event-source-mapping:<uuid>, and it is taggable:CreateEventSourceMapping(and CloudFormation) storeTags, andTagResource/UntagResource/ListTagswork on the mapping ARN as on a function ARN - Layers — create, publish, attach to functions; layer ZIP content is extracted into
/optof the runtime container at invoke time, so Pythonimport, Noderequire, andLD_LIBRARY_PATHlookups resolve against attached layers exactly as on real AWS - Layer sharing across accounts: every layer operation accepts a layer ARN as
LayerNameand acts on the account and region that ARN names (so publishing through your own layer's ARN adds a version to that layer). ALayerNameoutside the model's length and pattern is refused withValidationExceptionbefore anything is looked up, except that the region of a layer ARN may be the request's own region even when it does not look like an AWS region (--region local), so the ARNs fakecloud mints there address their layer; the rest of the pattern (partition, 12-digit account, layer name, length) still applies.AddLayerVersionPermissionwrites the version's resource-based policy the way Lambda does:Principalmust be a 12-digit account ID, an account root ARN in the layer's partition, or*; an account ID becomes{"AWS": "arn:<partition>:iam::<account>:root"};OrganizationId(only withPrincipal*) adds aStringEqualsaws:PrincipalOrgIDcondition; onlylambda:GetLayerVersioncan be granted; a duplicateStatementIdis aResourceConflictException. The policy carries aRevisionIdthat stays the same until the policy changes, and a staleRevisionIdonAddLayerVersionPermission/RemoveLayerVersionPermissionis aPreconditionFailedException. Another account reads a version (GetLayerVersion,GetLayerVersionByArn) only when that policy grants it to the account, to everyone, or to the account's organization (membership comes from fakecloud's Organizations state); otherwise the call fails withAccessDeniedException: User: <caller> is not authorized to perform: lambda:GetLayerVersion on resource: <layer version ARN>, with the same answer for a version that does not exist.ListLayerVersions,PublishLayerVersion,DeleteLayerVersion,GetLayerVersionPolicy,AddLayerVersionPermissionandRemoveLayerVersionPermissionthrough another account's ARN are always refused withAccessDeniedException(a layer version policy cannot grant them) and never touch the caller's own account. At attach time (CreateFunction,UpdateFunctionConfiguration, CloudFormationAWS::Lambda::Function): a missing version of your own layer isInvalidParameterValueException: Layer version <arn> does not exist.; a version of another account's layer that fakecloud holds needs the same grant, elseAccessDeniedException(also for a missing version of that layer); a layer of another account that fakecloud holds no copy of at all (an AWS-published or third-party layer such as Powertools) attaches withCodeSize0 and nothing mounted, so templates that use public layers keep deploying. That last case does let a caller tell an unknown foreign layer name from an unshared one, which the read operations do not. A function keeps the layer versions it already attached when the owner later revokes the grant. - Environment variables: the function's own variables plus the environment real Lambda provides:
AWS_REGION/AWS_DEFAULT_REGION(the function's region), execution-role credentials (AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY/AWS_SESSION_TOKEN, a registered session for the function's role named after the function, so SDK calls sign asassumed-role/<role>/<function>and verify under--verify-sigv4), andAWS_LAMBDA_FUNCTION_NAME/_VERSION/_MEMORY_SIZE,AWS_LAMBDA_LOG_GROUP_NAME/_LOG_STREAM_NAME,AWS_EXECUTION_ENV.AWS_ENDPOINT_URLpoints the SDK back at fakecloud (overridable by setting it on the function). Reserved keys are rejected onCreateFunction/UpdateFunctionConfigurationwithInvalidParameterValueException, as on AWS. The execution role must trustlambda.amazonaws.com(the trust policy read is the one of the role the ARN names, in the account that owns it, and for another account's role also that of the same-named role in the function's account, which the session is minted for); under--iam strictit must also be in the caller's account (AccessDeniedException: Cross-account pass role is not allowed.otherwise;--iam softlogs the would-be denial), while the default mode accepts another account's role (e.g.000000000000templates) and mints the session in the function's account. Applied on create, update and CloudFormation alike - VPC config —
VpcConfigsubnets and security groups are looked up in EC2 onCreateFunction/UpdateFunctionConfiguration(and CloudFormation): unknown ids or ones spanning VPCs are rejected withInvalidParameterValueException, and the response reports the sharedVpcId(empty once detached) - Lambda Managed Instances: capacity providers (
CreateCapacityProviderand friends, CloudFormationAWS::Lambda::CapacityProvider) have ARNs of the formarn:aws:lambda:<region>:<account>:capacity-provider:<name>, and their name labels take the name or that ARN. A function created withCapacityProviderConfig(API or CloudFormationAWS::Lambda::Function) is stored with it and returns it in everyFunctionConfiguration(CreateFunction,GetFunction,GetFunctionConfiguration,ListFunctions,UpdateFunctionConfiguration,PublishVersion), withExecutionEnvironmentMemoryGiBPerVCpureported as 2.0 when unset. It is checked the way Lambda checks it: the config's shape and ranges (ValidationException); no SnapStart, noVpcConfig, a supported runtime (Java 21+, Python 3.13+, Node.js 22+, .NET 8+,provided.al2023), at least 2048 MB (the defaultMemorySizefor these functions) and a memory-to-vCPU ratio of 2, 4 or 8 GiB that fits the memory;PerExecutionEnvironmentMaxConcurrencyat most 64 per vCPU; the provider must be in the request region (InvalidParameterValueException: Capacity provider arn invalid) and exist (ResourceNotFoundException: Capacity provider not found: <arn>. ...), and under--iam strictbelong to the caller's account (AccessDeniedException: Cross-account pass capacity-provider is not allowed.). The request also needslambda:PassCapacityProvideron the provider under IAM enforcement.UpdateFunctionConfigurationretunes or moves a Managed Instances function's config (the whole update is re-checked) and refuses one on a Lambda (default) function (CapacityProviderConfig isn't supported for Lambda Default functions.).PublishVersion/UpdateFunctionCode/CreateFunctionwithPublishTo=LATEST_PUBLISHED(CloudFormationPublishToLatestPublished) create or replace the function's$LATEST.PUBLISHEDversion, readable with that qualifier and run by unqualified invokes; on a Lambda (default) functionPublishVersionrefuses it.ListFunctionVersionsByCapacityProviderlists every version on the provider ($LATEST,$LATEST.PUBLISHEDand numbered versions, withMaxItems/Markerpaging), a provider takes at most 100 function versions (FunctionVersionsPerCapacityProviderLimitExceededException), andDeleteCapacityProvideris refused withResourceConflictExceptionwhile any version uses it. Functions do not actually run on EC2 capacity: they execute in containers like any other function CreateFunctionwithPublishcreates version 1 from the initial configuration and answers with that version- Aliases and versions — publish, point aliases at versions; alias-based weighted routing (
RoutingConfig) is enforced at invoke time so traffic splits between versions exactly as on AWS - Concurrency controls — reserved concurrency enforced at invocation time: per-function reservation caps in-flight invocations and excess requests are rejected with
TooManyRequestsException(HTTP 429) andReason=ReservedFunctionConcurrentInvocationLimitExceeded UpdateFunctionCodefrom S3 —S3Bucket/S3Key/S3ObjectVersionfetches the ZIP from the fakecloud S3 implementation; the storedCodeSha256is the real SHA-256 of the fetched bytes- CloudWatch metrics — every invoke publishes
Invocations,Errors,Duration,Throttles, andConcurrentExecutionsto theAWS/Lambdanamespace, queryable viaGetMetricStatistics/GetMetricData - Resource-based policies — the statement API (
AddPermission/RemovePermission/GetPolicy) and the document API (PutResourcePolicy/GetResourcePolicy/DeleteResourcePolicy) address one policy per function or qualifier (a version and an alias each have their own; an invocation of a version or alias ARN is authorized against that qualifier's policy under--iam): aRevisionIdacts as an optimistic-concurrency precondition (PreconditionFailedExceptionon mismatch) and anAllowopen to every principal with noConditionis rejected withPublicPolicyException GetAccountSettings— returns realAccountUsagecounters (FunctionCount,TotalCodeSize) andAccountLimitso SDKs that pre-flight account quotas see live values- Bounded memory: on the Docker backend a function's container is limited to
MemorySizeplus its/tmpsize, because/tmpis a tmpfs charged to the same limit. A function filling/tmpis never killed for it; one overrunningMemorySizecan survive by up to the size of/tmp - Warm container reuse: subsequent invocations of the same function reuse the container; each version has its own warm pool, and a configuration change (environment, memory, timeout, role, handler, tags) starts a fresh instance once the old one finishes any in-flight invocation
- Lambda Runtime API: fakecloud serves the Runtime API (
2018-06-01) itself instead of relying on the Runtime Interface Emulator in the base images. Each execution environment getsAWS_LAMBDA_RUNTIME_API=fakecloud-runtime-<token>:<port>, a host name of its own that resolves to the fakecloud listener inside the container (--add-hoston Docker and Podman,hostAliaseson Kubernetes), so the official images' entrypoint runs the runtime directly, a custom runtime (provided.al2,provided.al2023) polls it as on Lambda, and an instance only ever sees and answers its own events./invocation/nextcarriesLambda-Runtime-Aws-Request-Id(theInvokerequest ID, also for asynchronous invocations and their retries),Lambda-Runtime-Deadline-Ms,Lambda-Runtime-Invoked-Function-Arn(qualified when the caller named a version or alias),Lambda-Runtime-Trace-IdandLambda-Runtime-Client-Context(fromX-Amz-Client-Context). The outcome is what the runtime reports:/responseis the result (buffered, or streamed withLambda-Runtime-Function-Response-Mode: streaming, whoseLambda-Runtime-Function-Error-Type/-Error-Bodytrailers turn it into a function error),/errorisUnhandledwith the posted error object, and/init/errorfails the invocation with the runtime's init error (Runtime.ImportModuleError...). A runtime that exits isRuntime.ExitError(RequestId: <id> Error: Runtime exited with error: exit status N,signal: killed,Runtime.OutOfMemorywhen the kernel killed it for memory), an invocation past its timeout isSandbox.Timedout, and both reset the execution environment; a raised error does not. A runtime gets Lambda's 10-second init limit, then the function timeout runs from when it takes the event; an init that overruns the limit counts against the function timeout from the end of the limit, init and handler together. As on Lambda, an environment's invoke phase ends only when the runtime and every extension have asked for their next event: work they do after the response keeps the environment reserved (the next event waits for it) and counts against the timeout, which resets the environment if it runs out. The timeout is enforced whatever the caller does: an invocation whose caller stops waiting keeps its environment until the invoke phase ends or the timeout resets it. An idle environment whose runtime exits is retired, and an event it never took runs on a fresh one. A buffered response over 6 MB, or a streamed one over 200 MB, isFunction.ResponseSizeTooLarge(the runtime gets413 RequestEntityTooLarge; a stream is cut off at the limit).LogType=Tailreturns only that invocation's output, stdout and stderr in the order they were written (read from the container runtime's timestamped logs), between Lambda'sSTART,ENDandREPORTlines (withInit Durationon a cold start). Container images must run a runtime interface client that readsAWS_LAMBDA_RUNTIME_API, as every AWS base image does; an image whose entrypoint starts the emulator itself never asks for events and times out, as it would on Lambda. External extensions (regular executable files in/opt/extensions, symlinks followed, from layers or baked into a container image) start before the runtime, as on Lambda, so function init code can already call them (an extension servinglocalhost:2773, say); they share the container's stdout and stderr. Every function's container runs a small/bin/shlauncher as its entrypoint, which starts the extensions, waits until fakecloud has seen them all register, then runs the function's own entrypoint and command (from itsImageConfigwhere set, applied as Docker applies an entrypoint override: anImageConfigthat setsEntryPointbut noCommandruns that entrypoint without the image'sCMD). The launcher works whateverUSERthe image runs as, and on Kubernetes the command, arguments and environment reach the container as written ($(VAR)is not expanded, as on Lambda). An extension that cannot be launched fails the init withExtension.LaunchError, one that exits withExtension.Crash, and one that never registers lets the init time out. An extension that exits later, while an invocation runs or between invocations, fails that invocation (or the next one) withExtension.Crashand resets the environment. They get the Extensions API (2020-01-01):registerforINVOKEandSHUTDOWN,event/next,init/errorandexit/error(which fail the invocation and reset the environment). The first event waits until every extension has finished its init, andSHUTDOWN(with a 2-second grace,shutdownReasonspindown,timeoutorfailure) comes before an environment is torn down. A container image without/bin/shruns its own entrypoint directly, without its extensions (on Docker and Podman; on Kubernetes, where the image cannot be inspected before it runs, such an image fails to start). On Kubernetes an image's entrypoint and command are read from its registry; when that fails it runs as is, without its extensions. The Telemetry and Logs APIs are not served. When fakecloud itself runs in a container, Lambda containers join its network and reach its own listener there (for the Runtime API and SDK calls alike), so any published port works, and a function's ownlocalhostreference to fakecloud's port is rewritten to that address too. Integrations and asynchronous invokes that name a version or alias run that version's code and configuration: the version is picked once when the event is queued (an alias's routing config included), every retry runs it, the destination record'sexecutedVersionnames it, and an event whose version or alias is deleted before a retry is dropped rather than run on$LATEST. An event queued for$LATEST.PUBLISHEDretries the code that was published when it was queued, even if the function is published again in between.Invoke(synchronous orEvent),InvokeWithResponseStreamand every integration resolve a qualifier the same way: an alias pointing at$LATESTruns the live function, and a version that was never published (my-fn:99) isResourceNotFoundException: Function not found: <function ARN>:99; a function that does not exist named with:$LATESTisFunction not found: <function ARN>:$LATEST, as on Lambda. Extension exits are read from the launcher's exit record, which fakecloud polls: every 250 ms while the environment is working, and every 5 seconds while it is idle, so an extension that ends between invocations is noticed within about 5 seconds. A droppedevent/nextrequest alone is not treated as a crash, because fakecloud does not freeze an idle environment as Lambda does and an extension's HTTP client may time out its long poll and ask again; the next event simply waits until the extension asks again. An extension that ends after it has been sentSHUTDOWNis not a crash - Function errors: a handler that throws, a runtime that exits or fails init, and a timeout all answer
Invokewith HTTP 200,X-Amz-Function-Error: Unhandledand the error object as the payload (Runtime.ExitError,Runtime.ImportModuleError,Sandbox.TimedoutwithRequestId: <id> Error: Task timed out after N.00 seconds). Integrations react to that flag the way AWS does (behaviour recorded on AWS): Step Functions fails the task with the error'serrorType(orLambda.Unknown) and recordsLambdaFunctionFailedfor a function ARN resource; a REST API proxy answers 502{"message": "Internal server error"}and an HTTP API 500{"message":"Internal Server Error"}(an HTTP API also fails a returned object carryingerrorMessage); Lambda authorizers answer 401 for anUnauthorizederror and otherwise 500 (AuthorizerConfigurationExceptionon REST APIs); a WebSocket$connectfailure refuses the connection; synchronous Cognito triggers (all but the custom senders) fail the call withUserLambdaValidationException"<Trigger>failed with error<message>.", including the hosted-UI token endpoint; SQS / Kinesis / DynamoDB Streams event source mappings retry the batch (SQS after the visibility timeout, redriving atmaxReceiveCount); Secrets Manager stops the rotation at the failing step; CloudFormation custom resources are invoked asynchronously and fail with "CloudFormation did not receive a response from your Custom Resource" afterServiceTimeoutwhen the handler never answers; and RDSaws_lambda.invokeraiseslambda invocation failed. Only an error the runtime reports is a function error: a handler that returns an object carryingerrorTypeanderrorMessagesucceeds, as on AWS (see the Runtime API below) - Async invoke destinations and retries: an
Eventinvocation (fromInvokeor from S3, SNS, EventBridge, Scheduler, CloudWatch Logs subscriptions and SES receipt rules) whose function returns an error is retriedMaximumRetryAttemptstimes (default 2, one minute then two minutes apart), and one Lambda could not start is retried with exponential backoff (1 second doubling to 5 minutes) without using up those retries, either way unless it would outliveMaximumEventAge; an event whose function was deleted is dropped and one whose function can never run (no code, unsupported runtime) is discarded at once; the outcome goes to theOnSuccess/OnFailuredestination (SQS, SNS, EventBridge, Lambda, or S3 for failures) as the AWS invocation record (requestContext.conditionSuccess/RetriesExhausted/EventAgeExceeded,approximateInvokeCount,responseContext.functionError, the error object asresponsePayload), and a discarded event goes as-is to the function'sDeadLetterConfigqueue or topic withRequestID(the invocation's request ID),ErrorCodeandErrorMessageattributes InvocationTypehonored —Eventreturns 202 and runs in the background,RequestResponseblocks for the result,DryRunvalidates without executing- Durable functions: invoking a function that has a
DurableConfigstarts a durable execution that the official durable execution SDKs run unmodified. See Durable functions - Service Quotas: with "Function and layer storage" (
L-2ACBD22F) enforced in Service Quotas,CreateFunction,UpdateFunctionCode,PublishVersionandPublishLayerVersionare refused withCodeStorageExceededExceptionwhen the code of every$LATEST, published version and layer version in the region would pass the applied value (off by default).GetAccountSettingsreports the applied concurrency and storage quotas, andPutFunctionConcurrencykeeps at least 100 executions unreserved
Durable functions
A function created with a DurableConfig (ExecutionTimeout, required; RetentionPeriodInDays, default 14 days; optional KMSKeyArn) is a durable function. Lambda's validation applies: a DurableConfig without ExecutionTimeout is InvalidParameterValueException, out-of-range values are ValidationException, UpdateFunctionConfiguration merges the members it is given into the stored configuration and refuses to add one to a function created without it. Code built on the official durable execution SDK runs in fakecloud's runtime containers without changes (exercised end to end with @aws/durable-execution-sdk-js and aws-durable-execution-sdk-python bundled in the deployment package): the SDK reaches fakecloud's CheckpointDurableExecution and GetDurableExecutionState through the container's AWS_ENDPOINT_URL.
- Starting executions:
Invokemust name a version, alias or$LATEST(an unqualified name is refused withInvalidParameterValueException: You cannot invoke a durable function using an unqualified ARN.). The execution is pinned to the resolved version and its ARN is returned inX-Amz-Durable-Execution-Arn.RequestResponsewaits for the whole execution, waits included (past Lambda's 15-minute invocation limit, as AWS was recorded doing; a request reattaching to an existing execution by name waits as long as that execution can run), and answers with its result, or withX-Amz-Function-Error: Unhandledand anerrorMessage/errorTypebody when it fails, is stopped or times out.Eventanswers 202 at once.DurableExecutionName(X-Amz-Durable-Execution-Name) is an idempotency key per function: the same name and payload return the existing execution, another payload isDurableExecutionAlreadyStartedException(anEventinvoke answers 202 with the existing execution and starts nothing). Event source mappings, SNS, EventBridge and the other cross-service triggers start an execution too when they target a version or alias of a durable function, and wait for it to end. - Replay: each invocation receives
DurableExecutionArn, aCheckpointToken,InitialExecutionState(the operation log; children of a finished context are left out unless it asked to replay them) andUpdatedOperationIds. Checkpoints are validated the way Lambda validates them (SerializationException,ValidationExceptionlisting every violated constraint, andInvalidParameterValueExceptionfor an invalid action, a status transition the operation does not allow, a changed name/type/parent, an unknown parent or one that is not a context, an operation updated twice, an EXECUTION update that is not last, oversized payloads). Every checkpoint rotates the token; a stale token isInvalid checkpoint token, except a retry carrying the sameClientToken, which gets the original answer. - Operations: steps (
START,SUCCEED,FAIL,RETRYwithNextAttemptDelaySeconds: the step isPENDINGuntil its next attempt, thenREADY), waits (START,CANCEL), contexts (START,SUCCEED,FAIL,ReplayChildren), callbacks and chained invokes (started by the SDK, completed by the service). When the function returnsPENDING, fakecloud invokes it again as soon as a wait elapses, a retry comes due, a callback completes or times out, or a chained invoke returns. - Callbacks:
SendDurableExecutionCallbackSuccess/Failure/Heartbeatcomplete or extend a started callback. Callback ids encode their execution the way AWS ids do; an id that does not decode isInvalidParameterValueException: Invalid callback id, and one whose callback already completed, timed out or whose execution ended isCallbackTimeoutException.TimeoutSecondsandHeartbeatTimeoutSecondstime the callback out (Callback.Timeout/Callback.Heartbeat). - Chained invokes:
context.invokecalls another function of the same account and region. A durable target (named with a version or alias) runs as a child durable execution; a plain function is invoked once and its result or error is recorded once the invocation that started it has ended (as on AWS, the result is in the history after that invocation'sInvocationCompleted). Stopping a child recordsChainedInvokeStoppedon its parent; stopping a parent leaves its children running. - Ending: the function's
SUCCEEDED/FAILEDanswer ends the execution.ExecutionTimeouttimes it out (Execution timed out after N seconds.). An invocation that crashes is retried with backoff (1, 1, 2, 3, 5 ... seconds), and one that answersPENDINGwith nothing pending is retried with doubling delays, until the next attempt would pass the execution timeout; the execution then fails with the last error. An answer without a validStatusfails it at once.StopDurableExecutionstops a running execution and reports the stop time (or the end time of one that already ended). - Customer managed keys: a
KMSKeyArnis checked against fakecloud's KMS when it is set or changed: the key must exist, be enabled and have a key policy that letslambda.amazonaws.comusekms:GenerateDataKeyandkms:Decrypt(AccessDeniedExceptionotherwise, as on AWS). An alias ARN resolves to its key; the AWS-managedalias/aws/lambdais refused, as on AWS, because its key policy does not let Lambda decrypt. A key outside the function's region isInvalidParameterValueException. Once the key is disabled, pending deletion or gone, the operations that read or write an execution's data (GetDurableExecutionandGetDurableExecutionHistorywith data,StopDurableExecution,SendDurableExecutionCallbackSuccess/Failure) answerKMSDisabledException/KMSInvalidStateException/KMSNotFoundException, while metadata reads (IncludeExecutionData=false,ListDurableExecutionsByFunction) keep working. Invocations and checkpoints keep running, which is what AWS was recorded doing for 17 minutes after the key was disabled. - Reading executions:
GetDurableExecution(IncludeExecutionData),GetDurableExecutionHistory(the full event history,InvocationCompletedevents included; payloads only withIncludeExecutionData=true,ReverseOrder,MaxItems/Marker),ListDurableExecutionsByFunction(newest first;Qualifier,DurableExecutionName, a single status inStatuses,StartedAfter/StartedBefore,ReverseOrder, pagination). Pagination markers name the last item returned, so executions or events added between pages neither repeat nor go missing. Finished executions are dropped after their retention period. - Persistence: executions are part of the Lambda snapshot. After a restart, suspended executions keep waiting for their timers and callbacks, and an invocation that was running when the server stopped runs again.
- Deleting a durable function answers 202 (Lambda deletes it asynchronously); plain functions answer 204.
Not modeled: the encryption itself (payloads are not stored encrypted, and Lambda's data-key cache, which on AWS delayed the effect of disabling a key on reads by about 4.5 minutes, is not emulated), payload truncation beyond the API limits, and the $LATEST.PUBLISHED qualifier.
Protocol
REST. Path-based routing for invoke operations, JSON for control plane.
Introspection
GET /_fakecloud/lambda/invocations— list invocations delivered by other services (SQS, Kinesis, DynamoDB Streams, SNS, EventBridge, ...) withfunctionArn,payload(the event, as structured JSON),source, andtimestampGET /_fakecloud/lambda/warm-containers— list currently warm containersPOST /_fakecloud/lambda/{function-name}/evict-container— force a cold start on the next invokeGET /_fakecloud/lambda/layer-content/{account-id}/{layer-name}/{version}.zip[?region=<region>]— download the raw layer ZIP. Returned as theContent.LocationfromPublishLayerVersionandGetLayerVersion(with the layer'sregion), so AWS SDK / Terraform clients that re-download a layer get the actual bytes. Withoutregionthe server's--regionis tried first, then the account's other regionsGET /_fakecloud/lambda/function-code/{account-id}/{function-name}/{latest|<version>}.zip[?region=<region>]: download a function's deployment package, returned asCode.LocationfromGetFunction; the sameregionrule applies
Event source mapping example: FilterCriteria + partial batch failure
import { LambdaClient, CreateEventSourceMappingCommand } from "@aws-sdk/client-lambda";
await new LambdaClient({ endpoint: "http://localhost:4566" }).send(
new CreateEventSourceMappingCommand({
FunctionName: "process-orders",
EventSourceArn: "arn:aws:sqs:us-east-1:000000000000:orders",
BatchSize: 10,
MaximumBatchingWindowInSeconds: 5,
// Only deliver paid orders.
FilterCriteria: {
Filters: [{ Pattern: '{"body": {"status": ["paid"]}}' }],
},
// Opt into partial-batch failure: Lambda returns
// {"batchItemFailures":[{"itemIdentifier":"<msgId>"}]}
// and only those messages stay on the queue for retry.
FunctionResponseTypes: ["ReportBatchItemFailures"],
})
);Cross-service triggers
Lambda is a target for most event-producing services:
- SQS -> Lambda — Event source mapping polls the queue
- Kinesis -> Lambda — Event source mapping polls shards
- DynamoDB Streams -> Lambda — Event source mapping polls stream records
- S3 -> Lambda — Bucket notifications
- SNS -> Lambda — Topic subscriptions
- EventBridge -> Lambda — Rule targets
- API Gateway v2 -> Lambda — HTTP API proxy integration
- Cognito -> Lambda — Triggers (pre-signup, post-confirmation, pre/post-auth, custom message, token generation, migration, custom auth challenge)
- Secrets Manager -> Lambda — Rotation (all 4 steps)
- CloudFormation -> Lambda — Custom resources via
ServiceToken - SES Inbound -> Lambda — Receipt rule actions
- Step Functions -> Lambda — Task state integrations
- CloudWatch Logs -> Lambda — Subscription filters
Gotchas
- Requires a Docker socket. Lambda needs access to
/var/run/docker.sockto start and stop containers. Only use in environments you trust — Docker socket access is effectively host-level privilege. - First invocation of a runtime pulls the image. Expect a slower first run while the Lambda runtime image downloads. Subsequent invocations are fast. For
PackageType=Imagefunctions, a transient failure pulling the function's image (rate limiting, a registry 5xx, a network timeout) is retried with backoff and falls back to a copy already cached locally; a deleted or access-denied image fails the start. - Cold vs. warm containers. fakecloud reuses containers between invocations for the same function. Force a cold start via
/_fakecloud/lambda/{name}/evict-container.