SkillSprout
Chapter 6 · Lesson 1
Advanced
6 min read

Lambda in a VPC, Extensions and Tuning

Overview

By default Lambda runs in an AWS-managed network with internet access but no route into your VPC. To reach a private RDS database, ElastiCache cluster or internal service, you attach the function to private subnets and security groups. The function then uses elastic network interfaces inside your VPC, and its outbound path is governed by your route tables.

It is like moving an employee from a shared co-working space into your company building: they can now use the internal file server, but to reach the outside world they must go through your building's reception (a NAT gateway) or a private service door (a VPC endpoint).

This lesson also covers Lambda extensions, which add monitoring or secret-fetching companions to the execution environment, and the configuration and tuning knobs the exam lists: memory, timeout, environment variables, concurrency, layers, triggers and destinations.

Key Concepts

  • A VPC-attached function needs subnet IDs and security groups; Lambda creates Hyperplane ENIs shared across environments, so cold-start penalties are small.
  • VPC functions have no internet access unless the subnet routes to a NAT gateway; do not put them in public subnets expecting a public IP.
  • Use VPC gateway endpoints (S3, DynamoDB) and interface endpoints (SQS, Secrets Manager, KMS) for private access to AWS services.
  • RDS Proxy pools connections so many concurrent Lambda environments do not exhaust database connections.
  • Extensions run as separate processes in the environment (internal) or as sidecar processes (external) and hook into lifecycle events.
  • Memory (128 MB to 10,240 MB) also scales CPU; timeout maximum is 15 minutes; /tmp is configurable up to 10 GB.
  • Environment variables are encrypted at rest and can use a customer-managed KMS key with encryption helpers for extra protection.
  • Destinations route async results (success or failure) to SQS, SNS, EventBridge or Lambda; a DLQ is the older alternative.

Detailed Notes

Attaching a function to a VPC

yaml
Resources:
  ReportFn:
    Type: AWS::Serverless::Function
    Properties:
      Handler: app.handler
      Runtime: python3.12
      MemorySize: 512
      Timeout: 30
      VpcConfig:
        SubnetIds: [!Ref PrivateSubnetA, !Ref PrivateSubnetB]
        SecurityGroupIds: [!Ref FnSecurityGroup]
      Policies:
        - AWSLambdaVPCAccessExecutionRole
        - AWSSecretsManagerGetSecretValuePolicy: { SecretArn: !Ref DbSecret }

The execution role needs the ENI permissions in AWSLambdaVPCAccessExecutionRole (ec2:CreateNetworkInterface, DescribeNetworkInterfaces, DeleteNetworkInterface). Spread subnets across at least two Availability Zones for resilience.

Reaching things from a VPC function

TargetWhat to add
RDS or Aurora in the same VPCSecurity group rule from the function SG to the DB port; RDS Proxy for pooling
Public internet or third-party APIPrivate subnet with route to a NAT gateway
S3 or DynamoDBGateway endpoint (free)
Secrets Manager, SQS, KMS, STSInterface endpoint with private DNS
Another VPCPeering or Transit Gateway

A very common exam symptom: a VPC-attached function times out calling an AWS API. The fix is a NAT gateway or the right interface endpoint, not a public IP.

Connection management for databases

Each concurrent execution is a separate environment holding its own connection. A burst of 1,000 invocations can exceed max_connections. Put RDS Proxy between Lambda and the database; the function authenticates with IAM or Secrets Manager and the proxy multiplexes. Create the connection outside the handler to reuse it across warm invocations.

Extensions

Extensions use the Extensions API to receive Init, Invoke and Shutdown events. Typical uses are observability agents (Datadog, CloudWatch Lambda Insights), the AWS Parameters and Secrets Lambda Extension that caches secrets and parameters on a local HTTP port, and security agents. Add them as layers. Extensions share the function's memory and add to init and shutdown time, and the time they take counts toward billed duration.

python
import json, os, urllib.request

def get_secret(name):
    req = urllib.request.Request(
        "http://localhost:2773/secretsmanager/get?secretId=" + name,
        headers={"X-Aws-Parameters-Secrets-Token": os.environ["AWS_SESSION_TOKEN"]})
    return json.loads(urllib.request.urlopen(req).read())["SecretString"]

Configuration and tuning

bash
aws lambda update-function-configuration --function-name report-fn \
  --memory-size 1024 --timeout 60 \
  --environment "Variables={TABLE=orders,LOG_LEVEL=INFO}"
aws lambda put-function-event-invoke-config --function-name report-fn \
  --maximum-retry-attempts 1 --maximum-event-age-in-seconds 3600 \
  --destination-config '{"OnFailure":{"Destination":"arn:aws:sqs:eu-west-1:111122223333:report-failures"}}'

Increase memory to buy CPU: a CPU-bound function at 1,024 MB can finish in half the time of 512 MB and cost about the same. Use the open-source AWS Lambda Power Tuning state machine or AWS Compute Optimizer recommendations to find the cost-optimal value. Use provisioned concurrency to remove cold starts and SnapStart (Java, Python, .NET) to restore from a snapshot.

Event lifecycle and errors

Synchronous invocations return errors to the caller. Asynchronous invocations are queued internally, retried up to 2 times by default and then sent to the destination or DLQ. Stream and SQS event source mappings retry according to the source: a failing Kinesis batch blocks the shard until it succeeds or expires unless you configure bisect batch, maximum retry attempts, and an on-failure destination.

Near-real-time processing

For streams use batch size and batching window to trade latency against efficiency, parallelization factor (up to 10 per shard) for throughput, and enhanced fan-out for dedicated read capacity.

Real World Example

A reporting service attached to a VPC to reach Aurora started failing intermittently with "too many connections" during month-end peaks, and its calls to the Stripe API began to hang. The team added RDS Proxy, moved connection creation outside the handler, and placed the functions in private subnets with a NAT gateway for Stripe plus interface endpoints for Secrets Manager. They also raised memory from 256 MB to 1,024 MB after Power Tuning showed lower total cost.

Architecture Diagram

VPC-attached Lambda
Architecture
AWS Cloud
VPC
Functionprivate subnet
RDS Proxy + DB
NAT / endpoints
Third-party API

Private data via security groups; outside access via NAT or endpoints.

  1. 1The function runs on ENIs inside private subnets.
  2. 2Database traffic stays in the VPC through a proxy and security groups.
  3. 3Outbound calls follow route tables to NAT or an endpoint.
  4. 4Results are returned or sent to a destination.

Best Practices

  • ✓Place VPC functions in private subnets across two or more AZs.
  • ✓Use RDS Proxy and reuse connections outside the handler.
  • ✓Prefer VPC endpoints to NAT for AWS service traffic to cut cost and exposure.
  • ✓Tune memory with measurements, not guesses; CPU scales with memory.
  • ✓Configure destinations or DLQs and set max retries and event age for async invocations.

Common Interview Questions

Exam Tips

DVA-C02 focus

  • Lambda in a VPC has no internet without NAT; public subnets do not help.
  • RDS Proxy is the answer to Lambda connection storms.
  • Maximum timeout is 15 minutes; memory up to 10,240 MB; /tmp up to 10 GB.
  • Destinations carry richer context than DLQs and support success as well as failure.

Finished this lesson?

0 of 46 lessons done · 0% of the course