Serverless Architecture Patterns
Serverless forces you to think in events.It isolates logic but increases integration complexity.The "Lambda Monolith" is a common anti - pattern where you shove an entire Express app into a single function. This defeats the purpose.
Pattern 1: The "Strangler Fig"(Migration)
Scenario: You have a massive legacy monolith API. You want to move to Serverless without rewriting everything at once.
Solution: Place an API Gateway in front of your legacy API.
1. Route / users to the legacy system.
2. Route / new- feature to a Lambda function.
3. Slowly rewrite endpoints one by one and point API Gateway to new Lambdas.
Eventually, the legacy system is "strangled."
Pattern 2: Fan - Out / Fan - In
Scenario: You need to process a video file.
Anti - Pattern: One giant Lambda function runs for 15 minutes processing the whole video. (It will timeout).
Solution:
1. Split: A Lambda splits the video into 100 small chunks.
2. Fan - Out: It publishes 100 messages to an SQS Queue.
3. Process: 100 concurrent Lambda instances wake up and process each chunk in parallel.
4. Fan - In: A final Lambda stitches the results together.
This reduces total processing time from 15 minutes to 15 seconds.
Pattern 3: The "Queue-Based Load Leveling"
Scenario: Your site goes viral. 100,000 users hit your API at once. Your database (RDS) crashes because it maxes out connections.
Solution: Don't write to DB directly.
1. API Gateway -> Lambda -> SQS Queue .
2. The API returns "202 Accepted" instantly.
3. A throttled Lambda worker reads from the Queue at a safe pace(e.g., 50 records / sec) and writes to DB.
The queue absorbs the pressure.
The Cold Start Reality
If your function sleeps, AWS kills the container.The next request waits for a boot(200ms - 2s).
Mitigation Strategies:
- Ping it: A CloudWatch rule that invokes it every 5 min. (Hack)
- SnapStart: Java feature that resumes a snapshot of memory.
- Provisioned Concurrency: Pay AWS to keep N warm. (Expensive)
- Go / Rust: Use compiled languages with near-zero startup time instead of Node/Java.
Conclusion
Serverless is not just "Function as a Service." It is "Managed Services as First Class Citizens." The best code is the code you don't write. Use SQS, SNS, and EventBridge to handle logic you used to write in while loops.