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 Tags on create and TagResource / UntagResource / ListTags on 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 reserved aws: namespace and at most 50 tags per resource, counting the ones it already has (InvalidParameterValueException). Under --iam strict the tagging operations are authorized against the tagged resource's ARN, and a create that carries Tags also needs lambda:TagResource on 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-ErrorType header and the JSON body carries the error shape's own members, as recorded on AWS: {"Type":"User","Message":"Function not found: ..."} for ResourceNotFoundException, {"Type":"User","message":"..."} for errors whose model names the member message (InvalidParameterValueException, ResourceConflictException, ...), {"Message":"..."} with no Type for the KMS errors of durable functions (KMSDisabledException, KMSInvalidStateException) and for AccessDeniedException, "Type":null where 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, ListFunctions returns the request region's functions only, and a function ARN from another region is refused with ResourceNotFoundException: Functions from '<region>' are not reachable in this region ('<region>'). An Invoke by 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 -preview base 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 Kinesis data decode), StartingPosition (TRIM_HORIZON / LATEST / AT_TIMESTAMP for Kinesis, TRIM_HORIZON / LATEST for DDB Streams), MaximumBatchingWindowInSeconds (SQS; a partial batch held for the window stays visible in the queue), and FunctionResponseTypes=[ReportBatchItemFailures] partial-batch failure semantics (SQS, Kinesis, DynamoDB Streams). An SQS mapping hands several batches to the function at once, at most ScalingConfig.MaximumConcurrency of 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 as ReceiveMessage does 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 past maxReceiveCount moves a message to the dead-letter queue. A message the mapping still has with the function is never received again by it, even with a VisibilityTimeout of 0. Kinesis and DynamoDB Streams mappings retry a failed batch with exponential backoff up to MaximumRetryAttempts (default -1, until the records expire), drop batches older than MaximumRecordAgeInSeconds, split a failing batch with BisectBatchOnFunctionError, and send a discarded batch's KinesisBatchInfo / DDBStreamBatchInfo record to the OnFailure destination (SQS, SNS, or S3 with the batch's event as payload), as recorded on AWS; a batch Lambda cannot run at all is retried without using up retries. CreateEventSourceMapping refuses 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 (EventSourceArn a 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 by ConsumerGroupId (the mapping's UUID by default). A ConsumerGroupId must be unique among the region's Kafka mappings: creating a second mapping (API or CloudFormation) in a group another mapping uses is ResourceConflictException, and the consumer never commits an offset below what the group has already committed. Records are read with the read_committed isolation 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 in LastProcessingResult and skipped while the other partitions keep being delivered. A partition the group has no committed offset for starts at StartingPosition (TRIM_HORIZON, LATEST, or AT_TIMESTAMP with StartingPositionTimestamp), and that position is committed as the mapping starts. Records are batched up to BatchSize (default 100), the 6 MB invocation payload limit or MaximumBatchingWindowInSeconds (500 ms by default) and delivered as Lambda's Kafka event: eventSource aws:kafka with eventSourceArn, or SelfManagedKafka, bootstrapServers, and records keyed <topic>-<partition> with topic, partition, offset, timestamp, timestampType, base64 key / value (left out when null) and headers as byte arrays. FilterCriteria patterns see value decoded (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, BisectBatchOnFunctionError and the SQS / SNS / S3 OnFailure destination (a KafkaBatchInfo record) apply as for streams, and ReportBatchItemFailures responses are not interpreted (a batch succeeds or fails whole). LastProcessingResult reports OK, PROBLEM: Function call failed, or the connection, topic or authentication problem the poller hit. Self-managed brokers are reached over PLAINTEXT, or SASL_PLAINTEXT with BASIC_AUTH (SASL/PLAIN), SASL_SCRAM_256_AUTH or SASL_SCRAM_512_AUTH credentials read from the Secrets Manager secret ({"username","password"}); CLIENT_CERTIFICATE_TLS_AUTH, SERVER_ROOT_CA_CERTIFICATE and OAUTHBEARER are refused in LastProcessingResult. An MSK cluster's broker serves every client on its PLAINTEXT listener, so an MSK mapping's SASL_SCRAM_512_AUTH / CLIENT_CERTIFICATE_TLS_AUTH settings are checked against the cluster (the scheme enabled, the SCRAM secret associated with the cluster and readable) rather than negotiated. The Queue consumption mode and SchemaRegistryConfig are refused in LastProcessingResult. 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 RUNNING with a container runtime available): ActiveMQ over STOMP, RabbitMQ over AMQP 0-9-1, reading the one queue in Queues (RabbitMQ: in the virtual host of the VIRTUAL_HOST source access configuration, / by default) as the username / password of the BASIC_AUTH Secrets Manager secret. Messages are batched up to BatchSize (default 100), for at most MaximumBatchingWindowInSeconds after the first (default 500 ms) and under the 6 MB payload limit, and the function gets AWS's event: aws:mq with messages[] (messageID, messageType, timestamp, deliveryMode, correlationID, replyTo, destination.physicalName, redelivered, type, expiration, priority, base64 data, brokerInTime, brokerOutTime, properties) for ActiveMQ, aws:rmq with rmqMessagesByQueue keyed <queue>::<virtual host> (basicProperties, redelivered, base64 data) 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. FilterCriteria applies to the message with its data decoded 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 reports PROBLEM: 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). LastProcessingResult reports OK, 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's brokerInTime is 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: BatchSize defaults to 10 for SQS and 100 for every other source. A Kafka mapping always carries its AmazonManagedKafkaEventSourceConfig / SelfManagedKafkaEventSourceConfig, with ConsumerGroupId defaulting to the mapping's UUID and SchemaRegistryConfig (URI, EventRecordFormat, AccessConfigs, SchemaValidationConfigs) checked against the model. ConsumerGroupId (and a self-managed mapping's ConsumptionMode) cannot be changed by UpdateEventSourceMapping, while the schema registry can. ScalingConfig (SQS), ProvisionedPollerConfig (SQS and Kafka, with the documented MinimumPollers / MaximumPollers defaults and per-source bounds) and LoggingConfig (Kafka) are refused on sources that do not take them, and an empty one on update removes the setting. EventSourceMappingArn is arn:aws:lambda:<region>:<account>:event-source-mapping:<uuid>, and it is taggable: CreateEventSourceMapping (and CloudFormation) store Tags, and TagResource / UntagResource / ListTags work on the mapping ARN as on a function ARN
  • Layers — create, publish, attach to functions; layer ZIP content is extracted into /opt of the runtime container at invoke time, so Python import, Node require, and LD_LIBRARY_PATH lookups resolve against attached layers exactly as on real AWS
  • Layer sharing across accounts: every layer operation accepts a layer ARN as LayerName and acts on the account and region that ARN names (so publishing through your own layer's ARN adds a version to that layer). A LayerName outside the model's length and pattern is refused with ValidationException before 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. AddLayerVersionPermission writes the version's resource-based policy the way Lambda does: Principal must 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 with Principal *) adds a StringEquals aws:PrincipalOrgID condition; only lambda:GetLayerVersion can be granted; a duplicate StatementId is a ResourceConflictException. The policy carries a RevisionId that stays the same until the policy changes, and a stale RevisionId on AddLayerVersionPermission / RemoveLayerVersionPermission is a PreconditionFailedException. 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 with AccessDeniedException: 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, AddLayerVersionPermission and RemoveLayerVersionPermission through another account's ARN are always refused with AccessDeniedException (a layer version policy cannot grant them) and never touch the caller's own account. At attach time (CreateFunction, UpdateFunctionConfiguration, CloudFormation AWS::Lambda::Function): a missing version of your own layer is InvalidParameterValueException: Layer version <arn> does not exist.; a version of another account's layer that fakecloud holds needs the same grant, else AccessDeniedException (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 with CodeSize 0 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 as assumed-role/<role>/<function> and verify under --verify-sigv4), and AWS_LAMBDA_FUNCTION_NAME/_VERSION/_MEMORY_SIZE, AWS_LAMBDA_LOG_GROUP_NAME/_LOG_STREAM_NAME, AWS_EXECUTION_ENV. AWS_ENDPOINT_URL points the SDK back at fakecloud (overridable by setting it on the function). Reserved keys are rejected on CreateFunction/UpdateFunctionConfiguration with InvalidParameterValueException, as on AWS. The execution role must trust lambda.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 strict it must also be in the caller's account (AccessDeniedException: Cross-account pass role is not allowed. otherwise; --iam soft logs the would-be denial), while the default mode accepts another account's role (e.g. 000000000000 templates) and mints the session in the function's account. Applied on create, update and CloudFormation alike
  • VPC config — VpcConfig subnets and security groups are looked up in EC2 on CreateFunction / UpdateFunctionConfiguration (and CloudFormation): unknown ids or ones spanning VPCs are rejected with InvalidParameterValueException, and the response reports the shared VpcId (empty once detached)
  • Lambda Managed Instances: capacity providers (CreateCapacityProvider and friends, CloudFormation AWS::Lambda::CapacityProvider) have ARNs of the form arn:aws:lambda:<region>:<account>:capacity-provider:<name>, and their name labels take the name or that ARN. A function created with CapacityProviderConfig (API or CloudFormation AWS::Lambda::Function) is stored with it and returns it in every FunctionConfiguration (CreateFunction, GetFunction, GetFunctionConfiguration, ListFunctions, UpdateFunctionConfiguration, PublishVersion), with ExecutionEnvironmentMemoryGiBPerVCpu reported as 2.0 when unset. It is checked the way Lambda checks it: the config's shape and ranges (ValidationException); no SnapStart, no VpcConfig, a supported runtime (Java 21+, Python 3.13+, Node.js 22+, .NET 8+, provided.al2023), at least 2048 MB (the default MemorySize for these functions) and a memory-to-vCPU ratio of 2, 4 or 8 GiB that fits the memory; PerExecutionEnvironmentMaxConcurrency at 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 strict belong to the caller's account (AccessDeniedException: Cross-account pass capacity-provider is not allowed.). The request also needs lambda:PassCapacityProvider on the provider under IAM enforcement. UpdateFunctionConfiguration retunes 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 / CreateFunction with PublishTo=LATEST_PUBLISHED (CloudFormation PublishToLatestPublished) create or replace the function's $LATEST.PUBLISHED version, readable with that qualifier and run by unqualified invokes; on a Lambda (default) function PublishVersion refuses it. ListFunctionVersionsByCapacityProvider lists every version on the provider ($LATEST, $LATEST.PUBLISHED and numbered versions, with MaxItems/Marker paging), a provider takes at most 100 function versions (FunctionVersionsPerCapacityProviderLimitExceededException), and DeleteCapacityProvider is refused with ResourceConflictException while any version uses it. Functions do not actually run on EC2 capacity: they execute in containers like any other function
  • CreateFunction with Publish creates 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) and Reason=ReservedFunctionConcurrentInvocationLimitExceeded
  • UpdateFunctionCode from S3 — S3Bucket/S3Key/S3ObjectVersion fetches the ZIP from the fakecloud S3 implementation; the stored CodeSha256 is the real SHA-256 of the fetched bytes
  • CloudWatch metrics — every invoke publishes Invocations, Errors, Duration, Throttles, and ConcurrentExecutions to the AWS/Lambda namespace, queryable via GetMetricStatistics / 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): a RevisionId acts as an optimistic-concurrency precondition (PreconditionFailedException on mismatch) and an Allow open to every principal with no Condition is rejected with PublicPolicyException
  • GetAccountSettings — returns real AccountUsage counters (FunctionCount, TotalCodeSize) and AccountLimit so SDKs that pre-flight account quotas see live values
  • Bounded memory: on the Docker backend a function's container is limited to MemorySize plus its /tmp size, because /tmp is a tmpfs charged to the same limit. A function filling /tmp is never killed for it; one overrunning MemorySize can 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 gets AWS_LAMBDA_RUNTIME_API=fakecloud-runtime-<token>:<port>, a host name of its own that resolves to the fakecloud listener inside the container (--add-host on Docker and Podman, hostAliases on 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/next carries Lambda-Runtime-Aws-Request-Id (the Invoke request 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-Id and Lambda-Runtime-Client-Context (from X-Amz-Client-Context). The outcome is what the runtime reports: /response is the result (buffered, or streamed with Lambda-Runtime-Function-Response-Mode: streaming, whose Lambda-Runtime-Function-Error-Type / -Error-Body trailers turn it into a function error), /error is Unhandled with the posted error object, and /init/error fails the invocation with the runtime's init error (Runtime.ImportModuleError ...). A runtime that exits is Runtime.ExitError (RequestId: <id> Error: Runtime exited with error: exit status N, signal: killed, Runtime.OutOfMemory when the kernel killed it for memory), an invocation past its timeout is Sandbox.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, is Function.ResponseSizeTooLarge (the runtime gets 413 RequestEntityTooLarge; a stream is cut off at the limit). LogType=Tail returns only that invocation's output, stdout and stderr in the order they were written (read from the container runtime's timestamped logs), between Lambda's START, END and REPORT lines (with Init Duration on a cold start). Container images must run a runtime interface client that reads AWS_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 serving localhost:2773, say); they share the container's stdout and stderr. Every function's container runs a small /bin/sh launcher 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 its ImageConfig where set, applied as Docker applies an entrypoint override: an ImageConfig that sets EntryPoint but no Command runs that entrypoint without the image's CMD). The launcher works whatever USER the 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 with Extension.LaunchError, one that exits with Extension.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) with Extension.Crash and resets the environment. They get the Extensions API (2020-01-01): register for INVOKE and SHUTDOWN, event/next, init/error and exit/error (which fail the invocation and reset the environment). The first event waits until every extension has finished its init, and SHUTDOWN (with a 2-second grace, shutdownReason spindown, timeout or failure) comes before an environment is torn down. A container image without /bin/sh runs 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 own localhost reference 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's executedVersion names 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.PUBLISHED retries the code that was published when it was queued, even if the function is published again in between. Invoke (synchronous or Event), InvokeWithResponseStream and every integration resolve a qualifier the same way: an alias pointing at $LATEST runs the live function, and a version that was never published (my-fn:99) is ResourceNotFoundException: Function not found: <function ARN>:99; a function that does not exist named with :$LATEST is Function 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 dropped event/next request 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 sent SHUTDOWN is not a crash
  • Function errors: a handler that throws, a runtime that exits or fails init, and a timeout all answer Invoke with HTTP 200, X-Amz-Function-Error: Unhandled and the error object as the payload (Runtime.ExitError, Runtime.ImportModuleError, Sandbox.Timedout with RequestId: <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's errorType (or Lambda.Unknown) and records LambdaFunctionFailed for 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 carrying errorMessage); Lambda authorizers answer 401 for an Unauthorized error and otherwise 500 (AuthorizerConfigurationException on REST APIs); a WebSocket $connect failure refuses the connection; synchronous Cognito triggers (all but the custom senders) fail the call with UserLambdaValidationException "<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 at maxReceiveCount); 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" after ServiceTimeout when the handler never answers; and RDS aws_lambda.invoke raises lambda invocation failed. Only an error the runtime reports is a function error: a handler that returns an object carrying errorType and errorMessage succeeds, as on AWS (see the Runtime API below)
  • Async invoke destinations and retries: an Event invocation (from Invoke or from S3, SNS, EventBridge, Scheduler, CloudWatch Logs subscriptions and SES receipt rules) whose function returns an error is retried MaximumRetryAttempts times (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 outlive MaximumEventAge; 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 the OnSuccess / OnFailure destination (SQS, SNS, EventBridge, Lambda, or S3 for failures) as the AWS invocation record (requestContext.condition Success / RetriesExhausted / EventAgeExceeded, approximateInvokeCount, responseContext.functionError, the error object as responsePayload), and a discarded event goes as-is to the function's DeadLetterConfig queue or topic with RequestID (the invocation's request ID), ErrorCode and ErrorMessage attributes
  • InvocationType honored — Event returns 202 and runs in the background, RequestResponse blocks for the result, DryRun validates without executing
  • Durable functions: invoking a function that has a DurableConfig starts 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, PublishVersion and PublishLayerVersion are refused with CodeStorageExceededException when the code of every $LATEST, published version and layer version in the region would pass the applied value (off by default). GetAccountSettings reports the applied concurrency and storage quotas, and PutFunctionConcurrency keeps 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: Invoke must name a version, alias or $LATEST (an unqualified name is refused with InvalidParameterValueException: You cannot invoke a durable function using an unqualified ARN.). The execution is pinned to the resolved version and its ARN is returned in X-Amz-Durable-Execution-Arn. RequestResponse waits 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 with X-Amz-Function-Error: Unhandled and an errorMessage/errorType body when it fails, is stopped or times out. Event answers 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 is DurableExecutionAlreadyStartedException (an Event invoke 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, a CheckpointToken, InitialExecutionState (the operation log; children of a finished context are left out unless it asked to replay them) and UpdatedOperationIds. Checkpoints are validated the way Lambda validates them (SerializationException, ValidationException listing every violated constraint, and InvalidParameterValueException for 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 is Invalid checkpoint token, except a retry carrying the same ClientToken, which gets the original answer.
  • Operations: steps (START, SUCCEED, FAIL, RETRY with NextAttemptDelaySeconds: the step is PENDING until its next attempt, then READY), waits (START, CANCEL), contexts (START, SUCCEED, FAIL, ReplayChildren), callbacks and chained invokes (started by the SDK, completed by the service). When the function returns PENDING, 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 / Heartbeat complete or extend a started callback. Callback ids encode their execution the way AWS ids do; an id that does not decode is InvalidParameterValueException: Invalid callback id, and one whose callback already completed, timed out or whose execution ended is CallbackTimeoutException. TimeoutSeconds and HeartbeatTimeoutSeconds time the callback out (Callback.Timeout / Callback.Heartbeat).
  • Chained invokes: context.invoke calls 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's InvocationCompleted). Stopping a child records ChainedInvokeStopped on its parent; stopping a parent leaves its children running.
  • Ending: the function's SUCCEEDED / FAILED answer ends the execution. ExecutionTimeout times 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 answers PENDING with 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 valid Status fails it at once. StopDurableExecution stops a running execution and reports the stop time (or the end time of one that already ended).
  • Customer managed keys: a KMSKeyArn is checked against fakecloud's KMS when it is set or changed: the key must exist, be enabled and have a key policy that lets lambda.amazonaws.com use kms:GenerateDataKey and kms:Decrypt (AccessDeniedException otherwise, as on AWS). An alias ARN resolves to its key; the AWS-managed alias/aws/lambda is refused, as on AWS, because its key policy does not let Lambda decrypt. A key outside the function's region is InvalidParameterValueException. Once the key is disabled, pending deletion or gone, the operations that read or write an execution's data (GetDurableExecution and GetDurableExecutionHistory with data, StopDurableExecution, SendDurableExecutionCallbackSuccess / Failure) answer KMSDisabledException / 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, InvocationCompleted events included; payloads only with IncludeExecutionData=true, ReverseOrder, MaxItems/Marker), ListDurableExecutionsByFunction (newest first; Qualifier, DurableExecutionName, a single status in Statuses, 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, ...) with functionArn, payload (the event, as structured JSON), source, and timestamp
  • GET /_fakecloud/lambda/warm-containers — list currently warm containers
  • POST /_fakecloud/lambda/{function-name}/evict-container — force a cold start on the next invoke
  • GET /_fakecloud/lambda/layer-content/{account-id}/{layer-name}/{version}.zip[?region=<region>] — download the raw layer ZIP. Returned as the Content.Location from PublishLayerVersion and GetLayerVersion (with the layer's region), so AWS SDK / Terraform clients that re-download a layer get the actual bytes. Without region the server's --region is tried first, then the account's other regions
  • GET /_fakecloud/lambda/function-code/{account-id}/{function-name}/{latest|<version>}.zip[?region=<region>]: download a function's deployment package, returned as Code.Location from GetFunction; the same region rule 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.sock to 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=Image functions, 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.

Source