

Also from Kynth Studios


Also from Kynth Studios


Also from Kynth Studios
1# AWS Serverless — Lambda, SAM, DynamoDB — Cursor Rules23You are an expert AWS developer building serverless applications with Lambda, API Gateway, DynamoDB, S3, and SAM/CloudFormation, using TypeScript.45## Code Style67- Use TypeScript strict mode for all Lambda function code. Never use `any`.8- Use ESM modules (`import/export`). Configure `"type": "module"` in package.json.9- Use `camelCase` for variables and functions, `PascalCase` for classes and interfaces, `UPPER_SNAKE_CASE` for constants and environment variables.10- Use `@aws-sdk/client-*` v3 modular SDK packages, not the monolithic `aws-sdk` v2.11- Import only the clients you need: `import { DynamoDBClient } from '@aws-sdk/client-dynamodb'`.12- Prefer `@aws-sdk/lib-dynamodb` (Document Client) over raw `DynamoDBClient` for simpler DynamoDB operations.13- Create SDK clients outside the handler function (module scope) for connection reuse across invocations.14- Use Powertools for AWS Lambda for structured logging, tracing, and metrics.1516## Lambda Handler Design1718- Keep handlers thin. Extract business logic into separate service modules.19- Handler structure: parse input -> validate -> call service -> format response -> return.20- Type all event inputs. Use `@types/aws-lambda` for Lambda event and context types:21 `APIGatewayProxyEventV2`, `SQSEvent`, `S3Event`, `DynamoDBStreamEvent`, etc.22- Return properly formatted responses for API Gateway:23```typescript24 return {25 statusCode: 200,26 headers: { 'Content-Type': 'application/json' },27 body: JSON.stringify({ data: result }),28 }29```30- Handle errors at the handler level. Return appropriate HTTP status codes for API handlers.31- Use environment variables for configuration. Never hardcode ARNs, table names, or endpoints.32- Keep Lambda packages small. Use tree-shaking and avoid bundling unnecessary dependencies.33- Use `esbuild` or `tsup` for bundling Lambda functions.3435## DynamoDB3637- Design tables for your access patterns first. Create an access pattern document before designing the schema.38- Use single-table design for related entities when access patterns benefit from it.39- Primary key design: choose partition key (PK) and sort key (SK) that support your main query patterns.40- Use Generic Attribute Names for single-table design: `PK`, `SK`, `GSI1PK`, `GSI1SK`, `EntityType`.41- Denormalize data — DynamoDB is not a relational database. Duplicate data to avoid joins.42- Use Global Secondary Indexes (GSIs) for alternate access patterns. Minimize the number of GSIs (cost).43- Use `ExpressionAttributeNames` and `ExpressionAttributeValues` in all queries to prevent injection.44- Use `UpdateExpression` with `SET`, `REMOVE`, `ADD`, `DELETE` operations for partial updates.45- Implement optimistic locking with version attributes and `ConditionExpression`.46- Use TTL (`TimeToLive`) for auto-expiring items (sessions, temporary tokens, logs).47- Use `BatchWriteItem` for bulk writes (max 25 items). Use `BatchGetItem` for bulk reads (max 100 items).48- Handle `ConditionalCheckFailedException` for race conditions.49- Use DynamoDB Streams for event-driven processing (change data capture).5051## SAM Template Design5253- Use AWS SAM (`template.yaml`) for all infrastructure definitions. Prefer SAM over raw CloudFormation for Lambda.54- Define globals for shared Lambda configuration:55```yaml56 Globals:57 Function:58 Runtime: nodejs20.x59 Timeout: 3060 MemorySize: 25661 Environment:62 Variables:63 TABLE_NAME: !Ref MainTable64```65- Use `AWS::Serverless::Function` for Lambda functions with event source mappings.66- Use `AWS::Serverless::Api` for API Gateway REST API, or `AWS::Serverless::HttpApi` for HTTP API (v2).67- Define DynamoDB tables with `AWS::DynamoDB::Table`. Include `BillingMode: PAY_PER_REQUEST` for serverless scaling.68- Use `!Ref`, `!GetAtt`, `!Sub`, and `!Join` for dynamic resource references. Never hardcode ARNs.69- Use parameter overrides for environment-specific values (stage, domain, feature flags).70- Organize large templates with nested stacks or AWS SAM `AWS::Include`.7172## API Gateway7374- Use HTTP API (v2) for REST APIs — it's faster and cheaper than REST API (v1).75- Define routes with event source mappings on Lambda functions.76- Use Lambda authorizers for custom auth logic, or Cognito authorizers for Cognito-backed auth.77- Enable CORS explicitly with allowed origins, methods, and headers.78- Use request validation with API Gateway models to reject malformed requests early.79- Use stage variables for environment-specific configuration.80- Implement throttling and usage plans to protect against abuse.81- Use custom domain names with Route 53 and ACM certificates.8283## Error Handling8485- Create a standardized error response format:86```typescript87 interface ErrorResponse {88 statusCode: number89 body: string // JSON: { error: { code: string, message: string, requestId: string } }90 }91```92- Use custom error classes: `ValidationError`, `NotFoundError`, `ConflictError`, `UnauthorizedError`.93- Map error types to HTTP status codes in a centralized error handler.94- Include `requestId` (from Lambda context) in all error responses for debugging.95- Log errors with full context using structured logging (Powertools Logger).96- Use Dead Letter Queues (DLQ) on async Lambda invocations (SQS, SNS) to capture failed events.97- Implement retry logic with exponential backoff for transient AWS service errors.98- Use `AWSError` type checking for SDK errors: `if (error.name === 'ConditionalCheckFailedException')`.99100## Logging and Monitoring101102- Use `@aws-lambda-powertools/logger` for structured JSON logging.103- Log at appropriate levels: `logger.error()`, `logger.warn()`, `logger.info()`, `logger.debug()`.104- Include correlation IDs across Lambda invocations for request tracing.105- Use `@aws-lambda-powertools/tracer` for X-Ray tracing. Annotate traces with custom metadata.106- Use `@aws-lambda-powertools/metrics` for CloudWatch custom metrics.107- Set up CloudWatch Alarms for: error rates, throttling, duration p99, DLQ depth.108- Never log sensitive data (PII, credentials, tokens). Use `logger.removeKeys()` to strip sensitive fields.109110## Testing111112- Use Vitest for unit tests. Mock AWS SDK clients with `aws-sdk-client-mock`.113- Test Lambda handlers by invoking them directly with typed event objects.114- Test business logic independently from Lambda-specific code.115- Use `sam local invoke` for local integration testing.116- Use `sam local start-api` for testing API Gateway integrations locally.117- Create test event JSON files for each event source type.118- Use DynamoDB Local for database integration tests.119- Test IAM permissions with `sam validate` and `cfn-lint`.120121## File Structure122123```124functions/125 get-user/126 handler.ts — Lambda handler127 index.ts — Entry point (re-exports handler)128 create-user/129 handler.ts130 index.ts131lib/132 services/133 user-service.ts — Business logic134 repositories/135 user-repo.ts — DynamoDB operations136 models/137 user.ts — Domain types138 utils/139 response.ts — HTTP response helpers140 errors.ts — Custom error classes141 dynamodb.ts — DynamoDB client and helpers142 middleware/143 auth.ts — Auth validation144 validation.ts — Input validation with Zod145events/146 get-user.json — Test events for local testing147 create-user.json148template.yaml — SAM template149samconfig.toml — SAM deployment config150tsconfig.json151package.json152```153154## Security155156- Follow the principle of least privilege for IAM roles. Each Lambda gets only the permissions it needs.157- Use resource-based policies: restrict DynamoDB access to specific table ARNs, not `*`.158- Use `AWS::Serverless::Function` `Policies` property with SAM policy templates: `DynamoDBCrudPolicy`, `S3ReadPolicy`.159- Validate and sanitize all input in Lambda handlers before processing.160- Use KMS for encrypting environment variables with sensitive values.161- Use Secrets Manager or SSM Parameter Store for secrets, not environment variables.162- Enable API Gateway throttling and WAF for public-facing APIs.163- Enable CloudTrail for auditing all API calls to AWS services.164- Use VPC configuration for Lambda functions that need to access VPC resources.165166## Performance167168- Initialize SDK clients at module scope (outside handler) for connection reuse.169- Use `MemorySize` strategically — more memory = more CPU = faster execution (and can be cheaper).170- Use Provisioned Concurrency for latency-sensitive functions to eliminate cold starts.171- Use Lambda Layers for shared code and large dependencies (reduces package size).172- Use DynamoDB `ProjectionExpression` to fetch only needed attributes.173- Enable DynamoDB Auto Scaling or use On-Demand billing mode.174- Use SQS with Lambda for async processing to smooth out traffic spikes.175- Use S3 Transfer Acceleration for large file uploads from distant clients.176- Use CloudFront for caching API responses and static assets.177- Monitor with CloudWatch Insights to find slow and expensive invocations.178
One repository carrying more than one format is the comparison this product exists for: does anyone actually write different content in each file, or is one a copy of the other?
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| survivorforge/cursor-rulesrules/ai-ml-python/.cursorrules · 17 | .cursorrules | teststylearchdeployment+2 | 81/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/api-microservices/.cursorrules · 17 | .cursorrules | buildteststylearch+5 | 92/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/database-sql/.cursorrules · 17 | .cursorrules | styletypessecuritydatabase+3 | 65/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/devops-docker/.cursorrules · 17 | .cursorrules | setupbuildteststyle+4 | 93/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/devops-infrastructure/.cursorrules · 17 | .cursorrules | buildteststylesecurity+3 | 93/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/django-rest/.cursorrules · 17 | .cursorrules | buildteststylearch+5 | 84/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/docker-devops/.cursorrules · 17 | .cursorrules | setupteststylearch+6 | 85/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/flutter-dart/.cursorrules · 17 | .cursorrules | teststylearchtypes+5 | 89/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/go-gin/.cursorrules · 17 | .cursorrules | testlint-formatstylearch+5 | 84/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/langchain-ai/.cursorrules · 17 | .cursorrules | testlint-formatstylearch+4 | 84/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/mobile-react-native/.cursorrules · 17 | .cursorrules | teststylearchtypes+7 | 89/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/nextjs-14-app-router/.cursorrules · 17 | .cursorrules | teststyletypestesting-strategy+3 | 71/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/nextjs-app-router/.cursorrules · 17 | .cursorrules | teststylearchtypes+5 | 81/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/nextjs-typescript/.cursorrules · 17 | .cursorrules | teststylearchtypes+5 | 81/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/nextjs/.cursorrules · 17 | .cursorrules | teststylearchtypes+5 | 81/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/nodejs-express-typescript/.cursorrules · 17 | .cursorrules | setupteststylearch+7 | 81/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/nodejs-express/.cursorrules · 17 | .cursorrules | testlint-formatstylearch+7 | 92/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/performance-optimization/.cursorrules · 17 | .cursorrules | styledatabaseapiperformance+2 | 65/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/python-django/.cursorrules · 17 | .cursorrules | testlint-formatstylearch+6 | 99/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/python-fastapi/.cursorrules · 17 | .cursorrules | testlint-formatstylearch+6 | 99/100 | 13 days ago |
A badge carrying the measured quality of the strongest agent config file in this repository, out of 100. It reads from this index every time somebody loads your page, so it changes when the measurement changes and there is nothing to keep up to date. Free, no account, and the value is not something you or we can set by hand.
[](https://rulestack.kynth.studio/configs/survivorforge-cursor-rules-rules-aws-serverless-cursorrules)Would rather not hotlink us? Every badge is also served in shields.io’s endpoint schema, so shields renders the image and your readers never talk to our domain:
Published by Toolproof, the masthead over this index and eight others. The method behind the number is at toolproof.kynth.studio/methodology, and the whole thing is readable as JSON with no key at /api.