Ojasa Mirai

Ojasa Mirai

Cloud

Loading...

Learning Level

🟢 Beginner🔵 Advanced
⚙️ Compute Services⚡ Serverless Functions🗄️ SQL Database Services📊 NoSQL Database Services📁 Storage Services🌐 Networking Services⚖️ Load Balancing Services🚀 CDN Services🔐 Security & Auth Services📊 Monitoring & Logging Services📬 Message Queue Services🔌 API Gateway Services🐳 Container Orchestration💾 Caching Services🌐 Domain & DNS Services💾 Backup & Recovery Services
Cloud/Cloud Concepts Comparison/Serverless Functions

⚡ Serverless Functions - Advanced Patterns

Performance Optimization

Cold Start Reduction

// 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;
};

Concurrency Management

// 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();

Advanced Patterns

Fan-out Pattern

// 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);
}

State Machine (Step Functions / Workflows)

{
  "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
    }
  }
}

Cost Optimization

Cost Analysis

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

Optimization Strategies

// 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;
}

Monitoring and Debugging

// 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();

Security Best Practices

// 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;
}

Comparison Table: Advanced Features

FeatureLambdaCloud FunctionsAzure Functions
Concurrency ControlReserved + ProvisionedBuilt-inScale limits
State MachinesStep FunctionsWorkflowsDurable Functions
MonitoringCloudWatchCloud LoggingApplication Insights
VPC SupportYesNo (Serverless VPC Connector)Yes
Container SupportYes (OCI)NoYes
Warmup StrategiesProvisioned concurrency--no equivalent--Premium plan

Key Takeaways

  • **Cold starts manageable** with provisioned concurrency
  • **Fan-out pattern** for parallel processing
  • **Batch optimizations** reduce invocation costs significantly
  • **Memory sizing critical** - test different configurations
  • **State machines** for complex workflows
  • **Monitoring essential** - functions are hard to debug
  • **Cost varies significantly** by provider and usage pattern
  • **Security requires careful IAM setup**

Recommendations

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

Python Docs

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

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn