How to write Node.js Lambda functions

Luke Hedger

The LEGO Group and AWS Community Builder

Serverless Days: Student Edition - Aug 2022

AWS Lambda

  • Serverless compute requires a novel approach and mindset
  • But... the basics of Lambda will still allow to gain benefits (cost, scale etc)
  • Reach for the advanced features as complexity grows

Lifecycle

  • Compute model → programming model
  • Init phase runs "code outside handler"
  • Invocation phase runs "code inside handler"

Concurrency Model

Lambda's unit of scale is concurrency

Work With Constraints

  • Maximum concurrent executions = 1,000

  • Maximum function duration = 15 minutes

  • Maximum memory allocation = 10,240 MB

Optimise with Lambda Insights

Runtime & Language

  • Choose runtime/language to suit use case and team
  • Use latest Node.js version when possible
  • Use arm64 architecture (AWS Graviton2)

Files and Folders

  • Prefer a single file per function over early abstractions
  • If the file/function grows substantially consider architecture
  • Use a directory structure that works for you and change if needed

Code Standards

  • Use Prettier's default rules
  • Keep ESLint rules to a minimum. Use someone else’s rules with caution
  • Keep config in root, not tied to specific functions or services

TypeScript

AWS SDK

Testing

Security

  • Keep dependencies updated, especially vulnerability patches
  • Apply the Principle of Least Privilege to IAM policies - i.e. do not use * (wildcards)!
  • Use the OWASP Serverless Top 10 to mitigate common serverless application security vulnerabilities

Observability

  • Monitor metrics for Concurrent Executions, Throttles and Errors
  • Route alarms to team chat
  • Use dashboards to view critical health

Powertools

  • Lambda Powertools for TypeScript
  • Logs, metrics and tracing

Resources

- Next: CDK Workshop cdkworkshop.com

- More from me twitter.com/level_out

- These slides 🤳👇

Thanks!

How to write Node.js Lambda functions

By Luke

How to write Node.js Lambda functions

In this talk, Luke will walk-through how to write the most awesome Node.js Lambda functions, from project initialization through to operation. We'll look at how AWS Lambda functions work and why this matters. We'll then explore the best practice for folder structure, code standards, static analysis, testing, security and monitoring. All by employing the latest and greatest standards, as used by serverless experts!

  • 263