Serverless Tip #1: Separate your business logic from Lambda-specific logic to make your code more portable and easier to test
Your business logic and Lambda-specific logic have different concerns. Lambda-specific concerns include, but are not limited to:
- Setting up SDK clients
- Fetching configuration
- Parsing the incoming request payload
- Calling business logic
- Generating a response
By shielding the business logic from those concerns, you make it more portable and testable.
Your business logic should not care if API Gateway or EventBridge invokes it. Ideally, business logic should not know that it’s running in Lambda.
For example, an API Gateway triggers a Lambda function on a POST endpoint. You’ve encountered problems where downstream services can’t keep up with request spikes.
To solve the issue, you move to a storage-first pattern via direct integration between API Gateway and SQS.
Now, SQS is the trigger for your function instead of API Gateway. Such a change should only require changes to the handler code, not the business logic.