API-Driven Serverless Architectures
API-driven architectures use synchronous APIs as the primary integration pattern. This lesson covers design patterns, trade-offs, and multi-cloud examples.
Simple Explanation
What it is
API-driven architecture means the request comes in, your function runs immediately, and the user waits for the response.
Why we need it
Many products depend on fast, synchronous responses: login, search, and checkout.
Benefits
- Simple request/response flow that is easy to reason about.
- Low latency when designed well.
- Clear error handling for clients.
Tradeoffs
- Tight coupling between services in the call chain.
- More cost per request when traffic is high.
Real-world examples (architecture only)
- Mobile app -> API Gateway -> Function -> Database.
- Partner API -> HTTP endpoint -> Function -> Response.
Pattern: API Gateway → Function → Database
AWS Implementation
Code Example:
# AWS Lambda with DynamoDB
import boto3
import json
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('products')
def lambda_handler(event, context):
product_id = event['pathParameters']['id']
try:
response = table.get_item(Key={'id': product_id})
item = response.get('Item', {})
return {
'statusCode': 200,
'body': json.dumps(item)
}
except Exception as e:
return {
'statusCode': 500,
'body': json.dumps({'error': str(e)})
}
Google Cloud Implementation
Code Example:
# Google Cloud Function with Firestore
from google.cloud import firestore
from flask import jsonify
db = firestore.Client()
def get_product(request):
product_id = request.args.get('id')
try:
doc = db.collection('products').document(product_id).get()
if doc.exists:
return jsonify(doc.to_dict())
else:
return jsonify({'error': 'Not found'}), 404
except Exception as e:
return jsonify({'error': str(e)}), 500
Trade-offs: API-Driven vs Event-Driven
| Aspect | API-Driven | Event-Driven |
|---|---|---|
| Latency | Low (synchronous) | Higher (async queues) |
| Coupling | Tight (caller waits) | Loose (async processing) |
| Throughput | Lower (per-request overhead) | Higher (batched) |
| Error handling | Caller handles errors | Retry policies + DLQs |
| Cost | Higher (per-request billing) | Lower (throughput-optimized) |
Best Practices
- Timeout handling: API requests must return within API Gateway limits (29s for API Gateway).
- Error responses: Return standard HTTP status codes (400, 401, 403, 404, 500).
- Connection pooling: Reuse database connections; avoid creating new ones per request.
- Caching: Use CloudFront (AWS) or Cloud CDN (GCP) for static responses.
- Authentication: Use API keys, OAuth, or managed identity (IAM).
Security Considerations
- Rate limiting: Prevent abuse via API Gateway throttling.
- Input validation: Sanitize all inputs to prevent injection attacks.
- Secrets management: Store credentials in AWS Secrets Manager or Google Secret Manager.
- CORS: Configure carefully for cross-origin requests.
When to Use API-Driven Architecture
✓ Low-latency, synchronous workflows ✓ User-facing APIs (REST, GraphQL) ✓ Real-time data retrieval ✓ Single tenant or small request volumes
✗ High-throughput batch processing ✗ Complex multi-step workflows ✗ Work that can tolerate delays
For hands-on implementation details, see Level 2 — Lesson 1: REST APIs on API Gateway.
Next Steps
- Lesson 3: Event-driven architectures for async workflows.
- Lesson 5: Error handling and retries in synchronous systems.