Guide · Amazon EFS · AWS Lambda · Serverless Storage

Amazon EFS with AWS Lambda for MCP Servers — Shared File System Mounts in Serverless Functions

Lambda functions are limited to 512 MB ephemeral storage in /tmp (upgradeable to 10 GB at extra cost) and that storage is not shared across function instances. For MCP servers implemented as Lambda functions, this means every cold-start container independently downloads large dependencies — embedding models, pre-compiled toolchains, shared dictionaries — adding seconds to initialization time and cost. Amazon EFS solves this by providing a persistent, shared NFS volume that all Lambda executions mount at a consistent path like /mnt/efs. One function writes the model once; every subsequent invocation reads it from EFS in milliseconds. This guide covers the full setup: EFS file system + access point creation, the Lambda function configuration, the security group chain (the most common source of mount failures), IAM authorization, cold start latency benchmarks, and Node.js read patterns.

TL;DR

Mount EFS in Lambda by adding a FileSystemConfig entry (Arn of the EFS access point + LocalMountPath) to the function config. The Lambda function and EFS mount target must be in the same VPC. The Lambda SG must allow outbound TCP 2049; the EFS SG must allow inbound TCP 2049 from the Lambda SG. The Lambda execution role needs elasticfilesystem:ClientMount (and ClientWrite if writing). Cold start adds 30–150 ms for the NFS mount. Use an access point (not the EFS root) — Lambda can only mount EFS via access points.

Why Lambda + EFS for MCP servers

MCP server Lambda functions often need data that is too large for environment variables, too expensive to fetch from S3 on every invocation, and too dynamic to bake into the deployment package. Common examples:

The tradeoff is that Lambda + EFS requires a VPC configuration (adds ~500 ms to cold starts on first deployment if ENI creation is pending) and the EFS mount itself adds 30–150 ms to every cold start. Warm invocations pay no mount overhead — the NFS connection is reused for the lifetime of the execution environment.

Prerequisites: VPC, subnets, and security groups

Lambda can only mount EFS when the function is configured with a VPC. The function's VPC, subnets, and the EFS mount target must all be in the same VPC and the subnets must be in the same AZ as the mount targets (or use the DNS-based discovery which picks the same-AZ mount target automatically).

# Step 1: Create the EFS security group (allows NFS from Lambda)
aws ec2 create-security-group \
  --group-name efs-lambda-sg \
  --description "EFS: inbound NFS from Lambda functions" \
  --vpc-id vpc-12345678

# Step 2: Create the Lambda security group
aws ec2 create-security-group \
  --group-name lambda-mcp-sg \
  --description "Lambda MCP server: outbound NFS to EFS" \
  --vpc-id vpc-12345678

# Step 3: EFS SG - allow inbound NFS from Lambda SG
aws ec2 authorize-security-group-ingress \
  --group-id sg-efs-lambda \
  --protocol tcp \
  --port 2049 \
  --source-group sg-lambda-mcp

# Step 4: Lambda SG - allow outbound NFS to EFS SG
# (default all-egress rule usually covers this, but if egress is restricted:)
aws ec2 authorize-security-group-egress \
  --group-id sg-lambda-mcp \
  --protocol tcp \
  --port 2049 \
  --destination-group sg-efs-lambda

# Lambda also needs outbound HTTPS (443) to reach AWS APIs
aws ec2 authorize-security-group-egress \
  --group-id sg-lambda-mcp \
  --protocol tcp \
  --port 443 \
  --cidr 0.0.0.0/0

The security group chain is the number-one source of EFS mount failures in Lambda. When Lambda reports Error: EFS file system mount failed due to timeout, it almost always means TCP 2049 is blocked — either inbound on the EFS SG or outbound on the Lambda SG.

Creating an EFS access point for Lambda

Lambda can only mount EFS via an access point — it cannot mount the root of the file system directly. The access point enforces a directory root and POSIX UID/GID. Use UID/GID 1000 (or match your Node.js process UID inside the Lambda execution environment, which is sbx_user1051 with UID 496, though Lambda's EFS integration overrides POSIX permissions via the access point PosixUser).

import { EFSClient, CreateAccessPointCommand } from "@aws-sdk/client-efs";

const efs = new EFSClient({ region: "us-east-1" });

const { AccessPointId, AccessPointArn } = await efs.send(
  new CreateAccessPointCommand({
    FileSystemId: "fs-0abc123def456",
    PosixUser: {
      Uid: 1000,
      Gid: 1000,
    },
    RootDirectory: {
      Path: "/lambda/mcp-models",
      CreationInfo: {
        OwnerUid: 1000,
        OwnerGid: 1000,
        Permissions: "755",
      },
    },
    Tags: [{ Key: "Service", Value: "lambda-mcp-server" }],
  })
);

// AccessPointArn: arn:aws:elasticfilesystem:us-east-1:123456789012:access-point/fsap-0xyz789
console.log("AccessPointArn:", AccessPointArn);

The RootDirectory.CreationInfo block tells EFS to create the directory with the specified ownership if it does not exist. Without this, the first Lambda invocation fails with Permission denied trying to access a directory that doesn't exist yet.

Configuring the Lambda function to mount EFS

The key parameter is FileSystemConfigs, which takes an array of objects each containing the access point ARN and a local mount path under /mnt/. The function must also have a VPC config pointing at the subnets and security groups where EFS mount targets exist.

import {
  LambdaClient,
  CreateFunctionCommand,
  UpdateFunctionConfigurationCommand,
} from "@aws-sdk/client-lambda";

const lambda = new LambdaClient({ region: "us-east-1" });

// Creating a new function with EFS mount
await lambda.send(new CreateFunctionCommand({
  FunctionName: "mcp-server-tools",
  Runtime: "nodejs22.x",
  Handler: "index.handler",
  Role: "arn:aws:iam::123456789012:role/lambda-mcp-role",
  Code: { ZipFile: functionZipBuffer },
  Timeout: 30,
  MemorySize: 1024,
  // VPC configuration — required for EFS
  VpcConfig: {
    SubnetIds: ["subnet-aaa111", "subnet-bbb222"],   // must have EFS mount targets
    SecurityGroupIds: ["sg-lambda-mcp"],
  },
  // EFS mount
  FileSystemConfigs: [
    {
      Arn: "arn:aws:elasticfilesystem:us-east-1:123456789012:access-point/fsap-0xyz789",
      LocalMountPath: "/mnt/efs",   // must start with /mnt/
    },
  ],
}));

// Adding EFS to an existing function:
await lambda.send(new UpdateFunctionConfigurationCommand({
  FunctionName: "mcp-server-tools",
  FileSystemConfigs: [
    {
      Arn: "arn:aws:elasticfilesystem:us-east-1:123456789012:access-point/fsap-0xyz789",
      LocalMountPath: "/mnt/efs",
    },
  ],
  VpcConfig: {
    SubnetIds: ["subnet-aaa111", "subnet-bbb222"],
    SecurityGroupIds: ["sg-lambda-mcp"],
  },
}));

You can configure up to one EFS mount per Lambda function (one FileSystemConfigs entry). To mount multiple directories from the same EFS file system in one function, create multiple access points and mount them at different paths — but each access point counts as one mount. The limit is one file system per function.

IAM — granting Lambda the EFS mount permission

The Lambda execution role needs elasticfilesystem:ClientMount for read-only access and additionally elasticfilesystem:ClientWrite to write files. Scope the resource to the specific access point ARN to enforce least privilege.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "EFSReadMount",
      "Effect": "Allow",
      "Action": [
        "elasticfilesystem:ClientMount"
      ],
      "Resource": "arn:aws:elasticfilesystem:us-east-1:123456789012:file-system/fs-0abc123def456",
      "Condition": {
        "StringEquals": {
          "elasticfilesystem:AccessPointArn":
            "arn:aws:elasticfilesystem:us-east-1:123456789012:access-point/fsap-0xyz789"
        }
      }
    }
  ]
}

// For a writer function (e.g., the setup function that downloads models):
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "EFSReadWrite",
      "Effect": "Allow",
      "Action": [
        "elasticfilesystem:ClientMount",
        "elasticfilesystem:ClientWrite"
      ],
      "Resource": "arn:aws:elasticfilesystem:us-east-1:123456789012:file-system/fs-0abc123def456",
      "Condition": {
        "StringEquals": {
          "elasticfilesystem:AccessPointArn":
            "arn:aws:elasticfilesystem:us-east-1:123456789012:access-point/fsap-0xyz789"
        }
      }
    }
  ]
}

Lambda also needs ec2:CreateNetworkInterface, ec2:DescribeNetworkInterfaces, and ec2:DeleteNetworkInterface for VPC access. These are included in the AWSLambdaVPCAccessExecutionRole managed policy — attach it to the execution role rather than inlining the permissions.

Reading and writing from Node.js

Once mounted, the EFS directory is available at /mnt/efs using standard Node.js fs module calls. No EFS-specific SDK is needed — it looks like a local directory to your code.

import fs from "fs";
import path from "path";

const MODEL_DIR = "/mnt/efs/models";
const MODEL_PATH = path.join(MODEL_DIR, "embedding-model.onnx");

// Read a large model file — cached by OS page cache after first read per warm container
export async function loadModel(): Promise<Buffer> {
  if (!fs.existsSync(MODEL_PATH)) {
    throw new Error(`Model not found at ${MODEL_PATH} — run the setup function first`);
  }
  // For large files, use createReadStream instead of readFileSync to avoid memory spike
  return new Promise((resolve, reject) => {
    const chunks: Buffer[] = [];
    const stream = fs.createReadStream(MODEL_PATH);
    stream.on("data", (chunk) => chunks.push(Buffer.from(chunk)));
    stream.on("end", () => resolve(Buffer.concat(chunks)));
    stream.on("error", reject);
  });
}

// Write an artifact to EFS from a tool
export async function saveArtifact(
  sessionId: string,
  filename: string,
  data: Buffer
): Promise<string> {
  const artifactDir = path.join("/mnt/efs", "artifacts", sessionId);
  fs.mkdirSync(artifactDir, { recursive: true });

  const artifactPath = path.join(artifactDir, filename);
  fs.writeFileSync(artifactPath, data);

  return artifactPath;  // return path for other tools to read from
}

For module-level initialization (the warm container optimization), load from EFS outside the handler so the data is reused across invocations in the same execution environment:

// Module-level: runs once per execution environment (not per invocation)
let cachedModel: Buffer | null = null;

async function getModel(): Promise<Buffer> {
  if (!cachedModel) {
    cachedModel = await loadModel();  // EFS read — ~100ms first time, 0ms after
  }
  return cachedModel;
}

export const handler = async (event: any) => {
  const model = await getModel();
  // ... use model for inference
};

Cold start latency impact

EFS adds latency to Lambda cold starts in two phases:

  1. VPC ENI attachment — when Lambda scales to a new execution environment, it creates or reuses a VPC network interface. ENI creation takes 1–2 seconds (but Lambda pre-warms ENIs in a pool, so in practice this adds ~0–500 ms for the first cold start in a new AZ). Subsequent cold starts reuse the pool and add <100 ms.
  2. NFS mount — establishing the NFS v4.1 connection to the EFS mount target adds 30–150 ms per cold start. This is a one-time cost per execution environment lifetime (which can last hours or days for a steady-state function).

Empirical latency profile for a 1024 MB Lambda function mounting EFS:

ScenarioAdded latencyNotes
First cold start in AZ (new ENI)500–1500 msENI creation; happens rarely after initial deployment
Subsequent cold starts (ENI pool)100–300 msNFS mount + ENI reuse
Warm invocation0 msNFS connection reused; EFS reads from OS page cache
First EFS read (cold, 100 MB file)~800 msNFS read bandwidth ~125 MB/s for General Purpose EFS
Subsequent EFS read (page cache warm)~1 msServed from Linux buffer cache, not NFS

The cold start penalty is acceptable if EFS eliminates a larger S3 download. A 1 GB model that takes 8 seconds to download from S3 on cold start becomes a 1-second NFS read on the first cold invocation (before page cache), then essentially free on subsequent invocations in the same execution environment.

If cold start latency is unacceptable (e.g., your SLA is <500 ms p99), use Lambda Provisioned Concurrency to keep execution environments warm, eliminating the cold start entirely.

Setup function pattern — writing to EFS before the main function runs

A common initialization pattern is a "setup Lambda" that runs once (or on demand) to populate the EFS directory with models, assets, or lookup tables. The main MCP server function then reads from EFS without downloading anything:

// setup-lambda/index.ts — runs once to populate EFS
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
import fs from "fs";
import path from "path";
import { Readable } from "stream";
import { pipeline } from "stream/promises";

const s3 = new S3Client({ region: "us-east-1" });
const MODEL_PATH = "/mnt/efs/models/embedding-model.onnx";
const LOCK_PATH  = "/mnt/efs/models/.download-complete";  // idempotency guard

export const handler = async () => {
  // Idempotency: skip if already downloaded
  if (fs.existsSync(LOCK_PATH)) {
    console.log("Model already downloaded, skipping");
    return { status: "already_complete" };
  }

  // Ensure directory exists
  fs.mkdirSync(path.dirname(MODEL_PATH), { recursive: true });

  // Stream model from S3 directly to EFS (no /tmp intermediary)
  const { Body } = await s3.send(new GetObjectCommand({
    Bucket: "my-mcp-models",
    Key: "embedding-model.onnx",
  }));

  await pipeline(
    Body as Readable,
    fs.createWriteStream(MODEL_PATH)
  );

  // Write lock file — subsequent setup Lambda invocations see this and skip
  fs.writeFileSync(LOCK_PATH, new Date().toISOString());

  console.log("Model downloaded to EFS at", MODEL_PATH);
  return { status: "complete", modelPath: MODEL_PATH };
};

Trigger the setup function via a CloudFormation Custom Resource or an EventBridge rule that fires once on stack deploy. The main MCP server function checks for the lock file and fails fast with a clear error message if the setup Lambda hasn't run yet.

Common errors and fixes

ErrorCauseFix
EFS file system mount failed due to timeoutSecurity group chain broken — TCP 2049 blockedVerify Lambda SG has outbound TCP 2049 to EFS SG; EFS SG has inbound TCP 2049 from Lambda SG; mount target is available
AccessDeniedException from EFSLambda execution role missing elasticfilesystem:ClientMountAttach IAM policy with ClientMount on the file system ARN, scoped to the access point ARN via Condition
EACCES: permission denied on file writeMissing elasticfilesystem:ClientWrite or POSIX UID mismatchAdd ClientWrite; check that access point PosixUser.Uid matches the UID your code runs as (Lambda runs as root by default; access point overrides apply regardless)
ENOENT: no such file or directory /mnt/efsFileSystemConfigs not set on the function, or mount path typoVerify FileSystemConfigs[0].LocalMountPath === "/mnt/efs" (must start with /mnt/)
InvalidParameterValueException: Only access points are supportedTried to use file system ARN directly in FileSystemConfigs instead of access point ARNUse the access point ARN (arn:aws:elasticfilesystem:...:access-point/fsap-...), not the file system ARN
Stale data between Lambda invocationsOS page cache not invalidated when another Lambda writes to the same fileEFS is a coherent NFS file system — writes from one Lambda are visible to others within NFS cache coherency window (~30s). For exact-read-after-write, use O_DIRECT or avoid concurrent writes to the same file.

Related guides