
Securing Serverless Apps on AWS: A Practical Guide to Lambda, API Gateway, and DynamoDB
Serverless removes servers to patch, but not the security work. This guide covers authentication, least-privilege Lambda roles, input validation, secrets, DynamoDB access control, throttling, WAF, and monitoring for a typical API Gateway, Lambda, and DynamoDB application.
"Serverless" doesn't mean "secure by default." AWS manages the servers, operating system, and runtime patching for Lambda, but your code, permissions, configuration, and data are still your responsibility. Under the Shared Responsibility Model, that's a lot of surface area.
This article walks through a security-first design for a common pattern: Amazon API Gateway → AWS Lambda → Amazon DynamoDB, with Amazon Cognito for users.

1. Authenticate at the Edge
Don't let unauthenticated requests reach your code if you can stop them earlier. API Gateway supports several authorizers:
- Amazon Cognito user pool (or JWT) authorizer: best for end users signing in to your app.
- IAM authorization: best for service-to-service calls signed with AWS credentials.
- Lambda authorizer: for custom logic, such as API keys from a partner or a third-party identity provider.
Rejecting a bad token at API Gateway means your function never runs, which is both safer and cheaper.
Authentication is not authorization. Your function must still check that the signed-in user is allowed to access that specific record. Broken object-level authorization, where user A can read user B's data by changing an ID in the URL, is one of the most common API flaws.
2. One Function, One Role, Least Privilege
Give every Lambda function its own IAM execution role with only the permissions it needs. A function that reads one table should not be able to write to it, let alone touch S3.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["dynamodb:GetItem", "dynamodb:Query"],
"Resource": "arn:aws:dynamodb:<REGION>:<ACCOUNT_ID>:table/Orders"
}
]
}Avoid sharing one broad role across all functions. If one function is compromised, the damage is limited to what its own role allows. Use IAM Access Analyzer to review and tighten roles over time.
3. Restrict Data Access in DynamoDB
You can enforce per-user data isolation in IAM itself using the
dynamodb:LeadingKeys condition key, so a role can only touch items whose partition key matches the caller's identity. This is most useful when users get their own credentials (for example, through a Cognito identity pool).{
"Effect": "Allow",
"Action": ["dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:Query"],
"Resource": "arn:aws:dynamodb:<REGION>:<ACCOUNT_ID>:table/UserNotes",
"Condition": {
"ForAllValues:StringEquals": {
"dynamodb:LeadingKeys": ["${cognito-identity.amazonaws.com:sub}"]
}
}
}Also enable encryption at rest (on by default, and you can choose a customer-managed KMS key), point-in-time recovery, and deletion protection on important tables.
4. Validate Every Input
Treat all input as untrusted, including data that arrives through API Gateway. Validation has two layers:
- At API Gateway: REST APIs support request validation against a JSON schema model, rejecting malformed requests before Lambda runs.
- In your code: validate again. Never rely on a single layer.
export const handler = async (event) => {
let body;
try {
body = JSON.parse(event.body ?? "{}");
} catch {
return { statusCode: 400, body: JSON.stringify({ message: "Invalid JSON" }) };
}
const { title } = body;
if (typeof title !== "string" || title.length < 1 || title.length > 100) {
return { statusCode: 400, body: JSON.stringify({ message: "Invalid title" }) };
}
// Safe to continue: use parameterized SDK calls, never string-built queries
return { statusCode: 200, body: JSON.stringify({ ok: true }) };
};Injection isn't limited to SQL. Event data can reach shell commands, file paths, templates, and other services. Avoid passing untrusted input to
eval , child_process , or similar functions.5. Handle Secrets Properly
- Never hard-code secrets in function code or in the deployment package.
- Environment variables are encrypted at rest, but they are visible to anyone who can read the function configuration. Don't put high-value secrets there.
- Use AWS Secrets Manager or SSM Parameter Store and fetch the value at runtime, caching it outside the handler so you don't call the service on every invocation.
- Give the function's role permission to read only the specific secret it needs.
import { SecretsManagerClient, GetSecretValueCommand } from "@aws-sdk/client-secrets-manager";
const client = new SecretsManagerClient({});
let cachedSecret;
async function getSecret() {
if (!cachedSecret) {
const res = await client.send(
new GetSecretValueCommand({ SecretId: "prod/my-app/api-key" })
);
cachedSecret = res.SecretString;
}
return cachedSecret;
}Caching has a trade-off: a rotated secret won't be picked up until the execution environment is recycled, so add a short expiry if you rotate often.
6. Protect Against Abuse and Cost Spikes
Serverless scales automatically, which also means an attacker (or a bug) can scale your bill. Add limits:
- API Gateway throttling and usage plans to cap request rates per client.
- Lambda reserved concurrency to cap how many copies of a function run at once, and to protect downstream databases from being overwhelmed.
- AWS WAF in front of REST APIs (and CloudFront) to block common attacks and rate-limit abusive IPs. Note that WAF attaches to REST APIs, not to HTTP APIs, so check which API type you use.
- AWS Budgets and billing alarms to catch unexpected spend early.
Also set sensible function timeouts and memory sizes. A function that can run for 15 minutes when it should finish in 3 seconds gives an attacker more room to cause harm.
7. Keep Dependencies and Code Clean
Most serverless functions are small, but they often pull in many packages.
- Run
npm audit(or your language's equivalent) and use dependency scanning in your CI pipeline.
- Use Amazon Inspector to scan Lambda functions and layers for known vulnerabilities.
- Keep runtimes current. AWS patches the managed runtime, but when a runtime version is deprecated, you must move to a newer one.
- Consider code signing for Lambda if you need to guarantee that only trusted, approved packages are deployed.
- Keep deployment packages small. Fewer dependencies means a smaller attack surface.
8. Be Careful With VPC and Network Access
You don't need to place every Lambda function in a VPC. Do it only when the function must reach private resources, such as an RDS database. If you do:
- Use private subnets and tightly scoped security groups.
- Use VPC endpoints for services like S3, DynamoDB, and Secrets Manager so traffic stays on the AWS network.
- Remember that a function in a VPC has no internet access unless you add a NAT gateway, which has its own cost.
9. Log, Trace, and Alert
You can't investigate what you didn't record.
- Send logs to CloudWatch Logs with a retention period, and never log secrets, tokens, or personal data.
- Use structured (JSON) logs with a request ID so you can follow one request across services.
- Enable AWS CloudTrail to track API activity in the account.
- Turn on Amazon GuardDuty, which includes Lambda network activity monitoring, and send findings to a central place with AWS Security Hub.
- Use AWS X-Ray for tracing, and create CloudWatch alarms for error rates, throttles, and unusual invocation spikes.
10. Deploy Safely
Define everything with infrastructure as code (AWS SAM, CDK, CloudFormation, or Terraform) so permissions are reviewed in pull requests instead of clicked together in the console. Scan templates for risky settings, and deploy from your pipeline using short-lived credentials (such as OIDC federation) instead of stored access keys.
Quick Checklist
- [ ] Authentication at API Gateway (Cognito, IAM, or Lambda authorizer)
- [ ] Per-record authorization checks inside the function
- [ ] One least-privilege role per function
- [ ] DynamoDB encryption, backups, and scoped access
- [ ] Input validation at the API and in code
- [ ] Secrets in Secrets Manager or Parameter Store, not in code
- [ ] Throttling, reserved concurrency, and WAF where supported
- [ ] Dependency scanning and Inspector for Lambda
- [ ] VPC only where needed, with endpoints
- [ ] Structured logs, CloudTrail, GuardDuty, and alarms
- [ ] IaC with a secure CI/CD pipeline
Conclusion
Serverless shifts the focus of security from patching servers to managing identities, permissions, inputs, and configuration. The good news is that the building blocks are strong: managed authentication, fine-grained IAM, built-in throttling, and deep logging. The work is to turn them on deliberately.
If you're short on time, start with three changes: a dedicated least-privilege role for each function, authentication at the API layer, and secrets moved out of your code. Those alone close many of the most common gaps.
What's the first security control you add to a new Lambda function? Share your approach in the comments.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article