CloudBrum
CloudBrum · Cloud decision-support platform
AWS Compute

AWS LambdaLast reviewedReading time~12 minLevelBeginner to advanced

Amazon Web Services · Compute · Serverless functions (FaaS)

Run code without owning servers. Upload a function, choose what should start it, and AWS runs it, scales it and charges you only for the time it runs. A strong fit for event-driven work and for APIs whose traffic comes in waves.

On this page (17 sections)

    Mind map: AWS Lambda at a glance

    AWS Lambda mind map AWS Lambda at a glance: Triggers: API Gateway, function URL, S3, SQS, SNS, EventBridge, Streams and schedules; Code & runtime: Node.js, Python, Java, .NET, Zip or container image, Layers & extensions; Configuration: Memory 128 MB to 10 GB, Timeout up to 15 minutes, Environment variables, /tmp; Security: Execution role, Resource-based policy, Secrets Manager, KMS; Scaling: Concurrency per Region, Reserved concurrency, Provisioned, SnapStart; Reliability: Retries and dead letters, Partial batch responses, Idempotent handlers; Pricing: Requests plus GB-seconds, Monthly free tier, Arm costs less per run; Operations: Logs, metrics, X-Ray, Versions and aliases, SAM, CDK, Terraform. AWS Lambda at a glance Serverless functions on AWS: the main building blocks and decisions CloudBrum Cloud decision-support platform CloudBrum API Gateway, function URL S3, SQS, SNS, EventBridge Streams and schedules Triggers Node.js, Python, Java, .NET Zip or container image Layers & extensions Code & runtime Memory 128 MB to 10 GB Timeout up to 15 minutes Environment variables, /tmp Configuration Execution role Resource-based policy Secrets Manager, KMS Security Concurrency per Region Reserved concurrency Provisioned, SnapStart Scaling Retries and dead letters Partial batch responses Idempotent handlers Reliability Requests plus GB-seconds Monthly free tier Arm costs less per run Pricing Logs, metrics, X-Ray Versions and aliases SAM, CDK, Terraform Operations AWS Lambda17-point analysis CloudBrum· 17-point cloud service analysis cloudbrum.com
    CloudBrum AWS Lambda at a glance · 17-point analysis Triggers API Gateway, function URL S3, SQS, SNS, EventBridge Streams and schedules Code & runtime Node.js, Python, Java, .NET Zip or container image Layers & extensions Configuration Memory 128 MB to 10 GB Timeout up to 15 minutes Environment variables, /tmp Security Execution role Resource-based policy Secrets Manager, KMS Scaling Concurrency per Region Reserved concurrency Provisioned, SnapStart Reliability Retries and dead letters Partial batch responses Idempotent handlers Pricing Requests plus GB-seconds Monthly free tier Arm costs less per run Operations Logs, metrics, X-Ray Versions and aliases SAM, CDK, Terraform CloudBrum · cloudbrum.com

    Free to share. The downloaded image includes the CloudBrum link.

    Key features (summary)

    • Starts on eventsA function can wake up for an HTTP call, a queue message, a file upload, a schedule, a database change or another AWS event.
    • Zip or container imageShip a small zip archive or a container image of up to 10 GB, and share libraries between functions with layers.
    • Scales by itselfLambda adds execution environments as events arrive, within your account and per-function concurrency limits, and removes them when traffic stops.
    • Memory sets the powerPick 128 MB to 10,240 MB. CPU and network share grow with memory, so a bigger setting can finish sooner.
    • Up to 15 minutes a runEach invocation can run for up to 900 seconds, which suits short jobs rather than long-lived processes.
    • Arm or x86Run on Graviton (arm64) for a lower price per millisecond, or on x86_64 when a library only exists for Intel and AMD.
    • Built-in HTTPS endpointA function URL gives a function its own HTTPS address, and response streaming can send large output as it is produced.
    • Versions and aliasesPublish immutable versions, point an alias such as prod at one, and shift traffic gradually between two versions.

    Basic concepts

    Function
    Your code plus its settings: runtime, handler, memory, timeout, permissions and environment variables.
    Handler
    The entry point Lambda calls with each event, written as the file and function name, for example lambda_function.handler.
    Event and trigger
    The event is the JSON data passed in. The trigger is the service or schedule that produces it, such as API Gateway, S3, SQS or EventBridge.
    Execution environment
    A small isolated sandbox that holds your code and its runtime. Lambda reuses it for later invocations until it is retired.
    Cold start
    The extra time when Lambda has to create a new execution environment, load your code and run its start-up code before the handler.
    Concurrency
    The number of invocations running at the same moment. Each Region has an account limit, and you can reserve or limit it per function.
    Execution role
    The IAM role the function assumes at run time. It decides which AWS services your code may call.
    Resource-based policy
    A policy on the function that says who may invoke it, for example a named API Gateway or bucket in a named account.
    Event source mapping
    A Lambda-managed poller that reads from a queue or stream (SQS, Kinesis, DynamoDB Streams and others) and calls your function with batches.
    Version and alias
    A version is an unchangeable snapshot of code and settings. An alias is a movable name, such as prod, that points at a version.
    Layer
    A zip of libraries or data that several functions can load, kept separate from the function code.
    Provisioned concurrency
    Execution environments Lambda keeps initialised and ready, for latency-sensitive functions. You pay for them while they are held.
    Idempotency
    Handling the same event twice without a harmful second effect. Lambda delivery is at least once, so duplicates will happen.

    How to create & configure it

    Create a function in the AWS console

    1. Open Lambda and choose Create functionIn the AWS console search for Lambda, pick your Region, then choose Create function and Author from scratch.
    2. Name it and choose a runtimeUse a clear name such as orders-processor. Pick the language runtime and, unless a library needs Intel or AMD, the arm64 architecture.
    3. Let Lambda create the execution roleThe default role only writes logs to CloudWatch. Add exactly the permissions your code needs later, and nothing wider.
    4. Add your codeEdit in the console for a first test, or upload a zip or container image. Make sure the handler setting matches your file and function name.
    5. Set memory, timeout and storageStart with 256 MB and a timeout a little above the normal run time. Raise memory if a run is slow, then check the result in the logs.
    6. Add configuration and secretsPut plain settings in environment variables. Keep passwords and keys in AWS Secrets Manager or Parameter Store, and read them at start-up.
    7. Connect a triggerAdd API Gateway, a function URL, an SQS queue, an S3 event or a schedule. For queues, set the batch size and turn on partial batch responses.
    8. Test and read the logsRun a test event in the console, then open the log group in CloudWatch. The REPORT line shows duration and the memory actually used.
    9. Make it safe to run in productionAdd a dead-letter queue or failure destination, set reserved concurrency to protect downstream systems, publish a version and point an alias at it.

    Tip: once the steps work by hand, define the function and its trigger as code with AWS SAM, the CDK or Terraform (see the code references) so every environment is built the same way.

    Common issues after configuration

    SymptomLikely causeWhat to check / fix
    Task timed out after N secondsTimeout too short, or a slow callFind the slow step in the logs or X-Ray. Add timeouts to your own network calls, then raise the function timeout only as far as needed.
    AccessDeniedException from your codeExecution role is missing a permissionRead the denied action in the error and add it to the role, scoped to the one resource. Check KMS key policies too.
    Caller gets not authorized to perform lambda:InvokeFunctionResource-based policy missingAdd a permission that lets the calling service (and, ideally, its exact ARN) invoke the function.
    Runtime.ImportModuleError or Cannot find moduleWrong handler or a package built for another platformCheck the handler string and folder layout, and build dependencies for the same architecture (arm64 or x86_64) and Linux.
    Out of memoryMemory setting too lowCompare Max Memory Used in the REPORT log line with the setting, raise the memory, and look for large files held in memory.
    429 TooManyRequestsExceptionConcurrency is used upCheck the account limit and any reserved concurrency. Request a higher quota, or put a queue in front to smooth out bursts.
    No internet or database access after joining a VPCNo route out of the subnetAdd a NAT gateway or VPC endpoints for the services you call, and check the security groups.
    A whole queue batch is retried because one message failedPartial batch responses are offTurn on ReportBatchItemFailures and return the IDs of only the failed messages.
    Messages reappear on the queueVisibility timeout shorter than the functionSet the queue visibility timeout to several times the function timeout (AWS suggests at least six times).
    The same order is processed twiceDelivery is at least onceMake the handler idempotent, for example with a conditional write on a unique ID.
    Slow first request after quiet periodsCold startTrim dependencies, create SDK clients outside the handler, and consider SnapStart or provisioned concurrency for latency-critical paths.
    Surprise billA loop, a retry storm or an open endpointLook for a function that writes to the source that triggers it, cap concurrency, add budgets and alerts, and secure public endpoints.

    Use cases: when and where to use it

    Good fit

    • APIs and webhooks with uneven traffic
    • Reacting to file uploads (resize an image, scan a document)
    • Queue and stream consumers
    • Scheduled jobs and housekeeping
    • Glue between AWS services and automation of routine operations
    • Short steps inside a larger workflow

    Consider something else

    • Servers that run all day or need a custom OS → Amazon EC2
    • Jobs longer than 15 minutes → AWS Batch or containers on AWS Fargate
    • Long-lived connections or in-memory state → containers on Amazon ECS or EKS
    • Always-busy, CPU-heavy services → a steady fleet of instances is often cheaper
    • Complex multi-step flows → AWS Step Functions with Lambda as one step

    Pros: why consider it?

    Why teams choose it

    • No servers or operating systems to patch
    • Scales up from zero and back down to zero
    • You pay for use, with a monthly free tier
    • Very wide choice of event triggers
    • Quick to build, test and ship small units
    • Built-in versions, aliases and gradual deployments

    Trade-offs to weigh

    • Runs are limited to 15 minutes
    • Cold starts add delay to some requests
    • Local testing of event-driven flows takes effort
    • Account and Region limits can throttle a busy function
    • Many small functions can sprawl without naming and ownership rules
    • Triggers and permissions tie your design to AWS

    Common threats, vulnerabilities & risks

    RiskSeverityWhy it mattersMitigation
    Over-broad execution roleHighAnyone who can run code in the function inherits every permission the role has.One role per function, only the actions and resources it needs, and permission boundaries for teams.
    Unprotected function URL or APIHighA public endpoint with no authentication lets anyone run your code and your bill.Use IAM or an authoriser, put API Gateway with AWS WAF in front, and throttle.
    Untrusted input used unsafelyHighEvent data can carry SQL, shell or path tricks, as with any web input.Validate and escape every field, use parameterised queries and never build commands from event data.
    Secrets in environment variables or logsMediumAnyone who can read the configuration or the logs can read the secret.Store secrets in Secrets Manager or Parameter Store, encrypt with KMS and never log them.
    Vulnerable dependencies or shared layersMediumA bad library runs with your function’s permissions.Scan packages (Amazon Inspector covers Lambda), pin versions and review third-party layers.
    Runaway loops and retry stormsMediumA function that triggers itself, or endless retries, can multiply cost fast.Use reserved concurrency, dead-letter queues, recursion protection and billing alerts.
    Permissive cross-account invokeMediumA broad resource policy lets other accounts call the function.Name the exact principal, source ARN and account in the policy.
    Unsupported runtimeLow–MedOld runtimes stop receiving security fixes and can no longer be updated.Track runtime end dates and upgrade on a schedule.
    No logging or tracingLow–MedFailures and abuse go unnoticed and are hard to trace across services.Structured JSON logs, X-Ray or OpenTelemetry, alarms on errors, throttles and duration.

    Performance optimisation

    • Measure, then size. Try several memory settings and keep the one with the best cost for the speed you need. The open-source AWS Lambda Power Tuning tool automates this.
    • Do start-up work once. Create SDK clients, open connections and load configuration outside the handler so warm runs skip them.
    • Keep the package small. Fewer and lighter dependencies mean a faster start. Tree-shake or bundle where the language allows it.
    • Choose arm64 where your code and libraries support it; many workloads run faster per dollar there.
    • Cut cold starts where users feel them. SnapStart (for Java, Python and .NET) or provisioned concurrency can keep latency steady. They do not combine, so pick one.
    • Skip the VPC unless you need private resources. Use VPC endpoints or a proxy such as RDS Proxy to avoid exhausting database connections.
    • Tune batches for queues and streams. A larger batch and a short batching window lower the number of invocations, within what your downstream can take.
    • Do not wait inside a function. Hand slow work to a queue or a workflow so you are not paying for idle time.

    Reduce monthly cost

    FinOps is the habit of managing cloud spend together with engineering. These are the FinOps checks that matter most for AWS Lambda.

    • Right-size memory. Over-sized memory wastes money, and under-sized memory makes runs longer. Measure both sides.
    • Use arm64. Duration is billed at a lower rate on Graviton, around a fifth cheaper in the published example prices.
    • Filter events at the source. Event filtering on SQS, Kinesis, DynamoDB Streams and EventBridge means the function runs only for events you care about.
    • Batch where you can. One invocation for ten messages is cheaper than ten invocations.
    • Shorten the run. Set client timeouts, avoid polling and move long waits out of the function.
    • Use provisioned concurrency sparingly. It is billed while held, so keep it for steady, latency-critical traffic and schedule it down off-peak.
    • Commit if usage is steady. Compute Savings Plans can apply to Lambda usage.
    • Watch the neighbours. API Gateway, NAT gateways, CloudWatch Logs ingestion, data transfer and KMS calls can cost more than the function itself.
    • Set log retention on every log group so logs do not grow forever.
    • Add budgets and anomaly alerts, and tag functions by team and product.

    Prices and free-tier amounts in this guide are examples from the public pricing page and differ by Region. Confirm the current numbers before you decide (see Pricing).

    Security optimisation

    • Give each function its own least-privilege role, scoped to named resources, not *.
    • Lock down invocation with a tight resource-based policy that names the calling service, account and source ARN.
    • Never leave a function URL or API open. Use IAM authentication, an authoriser or Amazon Cognito, and add AWS WAF for public APIs.
    • Validate all input and use parameterised queries. Treat every event field as untrusted.
    • Keep secrets in Secrets Manager or Parameter Store; use KMS keys you control when rules demand it.
    • Attach to a VPC only when needed, with narrow security groups and private endpoints for AWS services.
    • Use code signing to allow only trusted packages where your policy requires it.
    • Scan dependencies and images (Amazon Inspector) and review any third-party layer before use.
    • Keep runtimes current and retire functions you no longer use.
    • Record CloudTrail events, send structured logs to CloudWatch, and alarm on errors and throttles.

    Governance & compliance

    Guardrails

    • Required tags: Owner, Environment, CostCenter (tag policies and SCPs)
    • Service control policies to limit Regions and block risky settings
    • IAM permission boundaries for teams that create roles
    • Service Quotas and budgets to limit sprawl

    Continuous checks (AWS Config)

    • “lambda-function-public-access-prohibited”
    • “lambda-function-settings-check” (runtime, timeout, memory)
    • “lambda-dlq-check”
    • “lambda-inside-vpc” where private access is required

    For audits, use AWS CloudTrail for who-changed-what, AWS Config for configuration history and AWS Artifact to download compliance reports. AWS Lambda sits inside the scope of many assurance programmes, but compliance is shared: AWS secures the platform and you secure your code, permissions, data and settings.

    Reduce carbon footprint

    • Right-size and shorten runs. Less memory and less time mean less energy used for the same result.
    • Choose arm64 where it fits; it generally does the same work with less power.
    • Avoid polling and needless invocations by using events, filters and batching.
    • Pick lower-carbon Regions when latency, cost and data rules allow.
    • Let idle functions cost nothing. With no traffic nothing runs, which beats a half-empty server for spiky work.
    • Delete what you do not use, including old versions, layers, images and log groups.
    • Measure it. The AWS Customer Carbon Footprint Tool reports estimated emissions for your account; check what it covers for your usage.

    Pricing

    Purchase options

    Pay per use Flexible

    You pay for requests and for duration, which is memory multiplied by the time your code runs, billed per millisecond. Nothing is charged while idle.

    Monthly free tier Free

    Every account gets a standing monthly amount of requests and GB-seconds at no charge. Check the pricing page for the current figures.

    Compute Savings Plans Commit

    Commit to a steady hourly spend for one or three years for lower rates that can also apply to Lambda.

    Provisioned concurrency Latency

    Pay to keep a set number of environments ready, plus the usual request and duration charges when they run.

    What you actually pay for

    • Requests (per million invocations)
    • Duration in GB-seconds, at a lower rate on arm64 (depending on runtime and packaging, the start-up phase can be billed too)
    • Provisioned concurrency, if used
    • Ephemeral storage above the included amount
    • Data transfer out and the services around the function: API Gateway, CloudWatch Logs, NAT, KMS, X-Ray

    Rates differ by Region and change over time. Use the official AWS Lambda pricing page and the AWS Pricing Calculator for current figures.

    Important code references

    A small function that saves orders from an SQS queue, ignores duplicates, and reports only the failed messages so just those are retried. The CLI and Terraform tabs deploy it; the Python and C# tabs hold the handler. Replace the placeholder names and the account ID with your own.

    # Package the code and create a small function on Arm (Graviton)
    zip function.zip lambda_function.py
    
    aws lambda create-function \
      --function-name orders-processor \
      --runtime python3.13 \
      --architectures arm64 \
      --handler lambda_function.handler \
      --role arn:aws:iam::123456789012:role/orders-processor-role \
      --zip-file fileb://function.zip \
      --memory-size 256 \
      --timeout 30 \
      --environment "Variables={TABLE_NAME=orders}" \
      --tracing-config Mode=Active \
      --tags Env=dev,Owner=platform-team
    
    # Read from an SQS queue and report failures one message at a time
    aws lambda create-event-source-mapping \
      --function-name orders-processor \
      --event-source-arn arn:aws:sqs:ap-south-1:123456789012:orders \
      --batch-size 10 \
      --maximum-batching-window-in-seconds 5 \
      --function-response-types ReportBatchItemFailures \
      --scaling-config MaximumConcurrency=10
    
    # Never let this function use more than 20 concurrent executions
    aws lambda put-function-concurrency \
      --function-name orders-processor \
      --reserved-concurrent-executions 20
    
    # Try it with a test event (AWS CLI v2 needs the binary-format flag for JSON payloads)
    aws lambda invoke --function-name orders-processor \
      --cli-binary-format raw-in-base64-out \
      --payload file://test-event.json response.json
    # Assumes an SQS queue (aws_sqs_queue.orders) and a DynamoDB table (aws_dynamodb_table.orders) are defined elsewhere
    data "archive_file" "function" {
      type        = "zip"
      source_file = "${path.module}/lambda_function.py"
      output_path = "${path.module}/function.zip"
    }
    
    resource "aws_iam_role" "orders" {
      name = "orders-processor-role"
      assume_role_policy = jsonencode({
        Version = "2012-10-17"
        Statement = [{
          Effect    = "Allow"
          Action    = "sts:AssumeRole"
          Principal = { Service = "lambda.amazonaws.com" }
        }]
      })
    }
    
    resource "aws_iam_role_policy" "orders" {
      name = "orders-processor-access"
      role = aws_iam_role.orders.id
      policy = jsonencode({
        Version = "2012-10-17"
        Statement = [
          { Effect = "Allow", Action = ["sqs:ReceiveMessage", "sqs:DeleteMessage", "sqs:GetQueueAttributes"], Resource = aws_sqs_queue.orders.arn },
          { Effect = "Allow", Action = ["dynamodb:PutItem"], Resource = aws_dynamodb_table.orders.arn },
          { Effect = "Allow", Action = ["logs:CreateLogStream", "logs:PutLogEvents"], Resource = "${aws_cloudwatch_log_group.orders.arn}:*" },
          { Effect = "Allow", Action = ["xray:PutTraceSegments", "xray:PutTelemetryRecords"], Resource = "*" }
        ]
      })
    }
    
    resource "aws_cloudwatch_log_group" "orders" {
      name              = "/aws/lambda/orders-processor"
      retention_in_days = 30
    }
    
    resource "aws_lambda_function" "orders" {
      function_name    = "orders-processor"
      role             = aws_iam_role.orders.arn
      runtime          = "python3.13"
      architectures    = ["arm64"]
      handler          = "lambda_function.handler"
      filename         = data.archive_file.function.output_path
      source_code_hash = data.archive_file.function.output_base64sha256
      memory_size      = 256
      timeout          = 30
    
      environment {
        variables = { TABLE_NAME = aws_dynamodb_table.orders.name }
      }
    
      tracing_config {
        mode = "Active"
      }
    
      logging_config {
        log_format = "JSON"
        log_group  = aws_cloudwatch_log_group.orders.name
      }
    
      tags = {
        Env   = "dev"
        Owner = "platform-team"
      }
    }
    
    resource "aws_lambda_event_source_mapping" "orders" {
      event_source_arn                   = aws_sqs_queue.orders.arn
      function_name                      = aws_lambda_function.orders.arn
      batch_size                         = 10
      maximum_batching_window_in_seconds = 5
      function_response_types            = ["ReportBatchItemFailures"]
    
      scaling_config {
        maximum_concurrency = 10
      }
    }
    # lambda_function.py (no packages to add: boto3 is included in the Python runtime)
    import json
    import logging
    import os
    from decimal import Decimal
    
    import boto3
    from botocore.exceptions import ClientError
    
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    
    # Created once per execution environment and reused by later invocations
    table = boto3.resource("dynamodb").Table(os.environ["TABLE_NAME"])
    
    
    def save_order(order):
        """Write the order once. A repeated message is ignored, so retries are safe."""
        try:
            table.put_item(Item=order, ConditionExpression="attribute_not_exists(order_id)")
        except ClientError as err:
            if err.response["Error"]["Code"] != "ConditionalCheckFailedException":
                raise
    
    
    def handler(event, context):
        failed = []
        for record in event["Records"]:
            try:
                save_order(json.loads(record["body"], parse_float=Decimal))
            except Exception:
                logger.exception("could not process message %s", record["messageId"])
                failed.append({"itemIdentifier": record["messageId"]})
        return {"batchItemFailures": failed}
    // dotnet new classlib, then add these packages:
    //   Amazon.Lambda.Core, Amazon.Lambda.SQSEvents, Amazon.Lambda.Serialization.SystemTextJson, AWSSDK.DynamoDBv2
    // Handler setting: OrdersProcessor::OrdersProcessor.Function::Handler
    using System.Text.Json;
    using Amazon.DynamoDBv2;
    using Amazon.DynamoDBv2.Model;
    using Amazon.Lambda.Core;
    using Amazon.Lambda.SQSEvents;
    
    [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
    
    namespace OrdersProcessor;
    
    public class Function
    {
        // Created once per execution environment and reused by later invocations
        private static readonly AmazonDynamoDBClient Dynamo = new();
        private static readonly string Table = Environment.GetEnvironmentVariable("TABLE_NAME")!;
    
        public async Task<SQSBatchResponse> Handler(SQSEvent sqsEvent, ILambdaContext context)
        {
            var failures = new List<SQSBatchResponse.BatchItemFailure>();
            foreach (var message in sqsEvent.Records)
            {
                try
                {
                    using var doc = JsonDocument.Parse(message.Body);
                    var orderId = doc.RootElement.GetProperty("order_id").GetString()!;
                    await Dynamo.PutItemAsync(new PutItemRequest
                    {
                        TableName = Table,
                        Item = new Dictionary<string, AttributeValue> { ["order_id"] = new(orderId), ["body"] = new(message.Body) },
                        ConditionExpression = "attribute_not_exists(order_id)"
                    });
                }
                catch (ConditionalCheckFailedException)
                {
                    // Already saved: a repeated message is safe to skip
                }
                catch (Exception ex)
                {
                    context.Logger.LogError($"could not process {message.MessageId}: {ex.Message}");
                    failures.Add(new SQSBatchResponse.BatchItemFailure { ItemIdentifier = message.MessageId });
                }
            }
            return new SQSBatchResponse(failures);
        }
    }

    Best videos to explore

    Videos picked for this service. Each one is labelled with its source, opens on YouTube if you prefer, and loads only when you press play.

    Introduction to AWS Lambda - Serverless Compute on Amazon Web ServicesOfficial · AWS · Beginner · Watch on YouTube
    Optimizing AWS Lambda Performance and Cost for Your Serverless ApplicationsOfficial · AWS · Intermediate · Watch on YouTube
    What’s New: AWS Lambda event source mappingsOfficial · AWS · Intermediate · Watch on YouTube
    Errors and retries - Lambda Event Source Mapping with SQS triggerCommunity video · Intermediate · Watch on YouTube

    Interview questions

    BasicWhat is AWS Lambda?

    AWS Lambda is a serverless compute service. You provide a function, AWS runs it when an event arrives, scales it automatically and charges for the requests and the time it runs. You do not manage servers or operating systems.

    BasicWhat is a cold start?

    A cold start is the extra delay when Lambda must create a new execution environment, load your code and run its start-up code before handling the event. Later invocations that reuse a warm environment skip that work.

    BasicWhat are the main limits to remember?

    A run can last up to 15 minutes, memory is 128 MB to 10,240 MB, a zip upload is limited to 50 MB (250 MB unzipped), a synchronous payload is 6 MB and an asynchronous one is 1 MB. Limits change, so confirm them on the quotas page.

    IntermediateWhat is the difference between reserved and provisioned concurrency?

    Reserved concurrency sets aside a share of your account limit for one function and also caps it, which protects other functions and downstream systems. Provisioned concurrency keeps environments initialised and ready to avoid cold starts, and you pay for it while it is held.

    IntermediateHow do synchronous, asynchronous and polled invocations differ?

    With synchronous calls (API Gateway, a function URL) the caller waits for the result and handles errors. Asynchronous events (S3, SNS, EventBridge) are queued by Lambda and retried automatically. For SQS, Kinesis and DynamoDB Streams an event source mapping polls the source and calls the function with batches.

    IntermediateHow do you handle failures and retries?

    For asynchronous invocations configure retries, a dead-letter queue or an on-failure destination. For queues turn on partial batch responses so only failed messages return, and set a dead-letter queue on the source. In every case make the handler idempotent, because delivery is at least once.

    AdvancedHow would you make a Lambda function idempotent?

    Derive a unique key from the event (an order ID or message ID) and record it with a conditional write, so a second delivery finds the key and does nothing. Libraries such as Powertools for AWS Lambda offer an idempotency helper that stores keys in DynamoDB.

    AdvancedA function reads a queue and writes to a database that can only handle 50 connections. How do you design it?

    Limit the function’s concurrency with reserved concurrency or the event source’s maximum concurrency, reuse connections outside the handler, and put RDS Proxy or a connection pool in front of the database. A queue in the middle absorbs bursts without overloading the database.

    AdvancedWhen would you not choose Lambda?

    When work runs longer than 15 minutes, needs a custom OS or special hardware, holds long-lived connections or large in-memory state, or runs at a steady high load where a fleet of instances or containers costs less. Then consider EC2, containers on Fargate or AWS Batch.

    Similar or alternative services on other clouds

    CapabilityAWSAzureGoogle Cloud
    ServiceAWS LambdaAzure FunctionsCloud Run functions
    HTTP endpointFunction URL, API GatewayHTTP trigger, API ManagementHTTP function, API Gateway
    Event sourcesSQS, SNS, EventBridge, S3, KinesisQueue Storage, Service Bus, Event Grid, Event HubsPub/Sub, Eventarc, Cloud Storage
    Multi-step workflowsStep FunctionsDurable FunctionsWorkflows
    Warm capacityProvisioned concurrency, SnapStartAlways ready instances, Premium planMinimum instances
    Longest run15 minutesDepends on the plan: 10 minutes on Consumption, no enforced maximum on Flex and PremiumLonger for HTTP functions than for event-driven ones
    Billing unitRequests and GB-secondsExecutions and GB-seconds (Premium by vCPU and memory time)Requests plus vCPU-seconds and GiB-seconds
    Local developmentAWS SAM CLIAzure Functions Core ToolsFunctions Framework

    Not sure a function is the right size? Compare with Amazon EC2 for servers you control, AWS Fargate for containers without servers, and AWS Step Functions for workflows that call several functions.

    Did you find this article helpful?

    Your answer helps us improve this page for the next reader.

    Sources and further reading

    CloudBrum wrote this page in its own words, using the provider’s public documentation listed below as the reference. Features, limits, names and prices change, so confirm anything that matters on the provider’s own pages before you decide.