
Cloud
Learning Level
// Lambda function with provisioned concurrency
// Deploy with 10 warm instances ready
// Optimized function
const AWS = require('aws-sdk');
// Initialize outside handler (reused across warm starts)
const s3 = new AWS.S3();
const db = createDatabaseConnection(); // Pool created once
exports.handler = async (event) => {
// Fast path for cached data
const cached = await db.getFromCache(event.id);
if (cached) return cached;
// Actual processing
const result = await process(event);
await db.cache(event.id, result);
return result;
};// AWS Lambda: Reserved concurrency
// Set max concurrent executions per function
// Prevents function from consuming all account capacity
const lambda = new AWS.Lambda();
await lambda.putFunctionConcurrency({
FunctionName: 'myFunction',
ReservedConcurrentExecutions: 100
}).promise();
// Provisioned concurrency (warm instances)
await lambda.putProvisionedConcurrencyConfig({
FunctionName: 'myFunction',
ProvisionedConcurrentExecutions: 10,
Qualifier: 'LIVE'
}).promise();// Invoke multiple functions in parallel
async function processBatch(items) {
const promises = items.map(item =>
lambda.invoke({
FunctionName: 'processItem',
InvocationType: 'Event', // Async
Payload: JSON.stringify(item)
}).promise()
);
await Promise.all(promises);
}{
"Comment": "Process image workflow",
"StartAt": "ValidateInput",
"States": {
"ValidateInput": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:validate",
"Next": "ResizeImage"
},
"ResizeImage": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:resize",
"Next": "UpdateDatabase"
},
"UpdateDatabase": {
"Type": "Task",
"Resource": "arn:aws:dynamodb:us-east-1:123456789012:stateMachine:updateDB",
"End": true
}
}
}AWS Lambda:
Invocations: 1M calls × $0.0000002 = $0.20
Compute: 1M × 1s × 128MB × $0.0000166667 = $1.67
Total: ~$1.87 per 1M invocations
GCP Cloud Functions:
Invocations: 1M × $0.40 = $0.40
Compute: 1M × 1s × 256MB × $0.0000041667 = $4.17
Total: ~$4.57 per 1M invocations
Savings: Lambda ~$2.70 cheaper per 1M calls// 1. Batch processing to reduce invocations
async function batchProcess(records) {
const batches = [];
for (let i = 0; i < records.length; i += 100) {
batches.push(records.slice(i, i + 100));
}
for (const batch of batches) {
await processBatch(batch); // One invocation per 100 records
}
}
// 2. Minimize memory allocation
// 128MB vs 1GB = 8x difference in cost
// But slower execution = more time = more cost
// Find sweet spot: usually 512MB-1GB
// 3. Use caching to avoid recomputation
const NodeCache = require('node-cache');
const cache = new NodeCache({ stdTTL: 600 }); // 10 minutes
async function getUser(userId) {
const cached = cache.get(userId);
if (cached) return cached;
const user = await db.getUser(userId);
cache.set(userId, user);
return user;
}// CloudWatch integration
const AWSXRay = require('aws-xray-sdk-core');
exports.handler = AWSXRay.captureAsyncFunc('processRequest',
async (event) => {
// Automatic tracing of AWS SDK calls
const result = await s3.getObject({
Bucket: 'my-bucket',
Key: event.fileName
}).promise();
return result;
}
);
// Custom metrics
const CloudWatch = new AWS.CloudWatch();
await CloudWatch.putMetricData({
Namespace: 'MyApp/Functions',
MetricData: [{
MetricName: 'ProcessingTime',
Value: endTime - startTime,
Unit: 'Milliseconds'
}]
}).promise();// 1. IAM roles (least privilege)
// Attach only necessary permissions
// 2. Secrets management
const secretsManager = new AWS.SecretsManager();
const secret = await secretsManager.getSecretValue({
SecretId: 'myDatabasePassword'
}).promise();
// 3. VPC execution for database access
// Lambda runs in VPC with security groups
// 4. Input validation
function validateInput(event) {
if (!event.userId || typeof event.userId !== 'number') {
throw new Error('Invalid userId');
}
if (event.userId < 0 || event.userId > 1000000) {
throw new Error('userId out of range');
}
return true;
}| Feature | Lambda | Cloud Functions | Azure Functions |
|---|---|---|---|
| Concurrency Control | Reserved + Provisioned | Built-in | Scale limits |
| State Machines | Step Functions | Workflows | Durable Functions |
| Monitoring | CloudWatch | Cloud Logging | Application Insights |
| VPC Support | Yes | No (Serverless VPC Connector) | Yes |
| Container Support | Yes (OCI) | No | Yes |
| Warmup Strategies | Provisioned concurrency | --no equivalent-- | Premium plan |
High-Traffic APIs: Lambda with reserved concurrency
Batch Processing: Cloud Functions (simple) or Durable Functions (complex)
Real-time Events: Firebase for real-time DB triggers
Cost Sensitive: GCP if low latency not critical
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward