AWS Lambda Cost Optimization: Lessons from Production

Foundry24

After managing Lambda functions processing millions of invocations monthly, we’ve learned a few things about keeping costs under control.

The Hidden Costs

Lambda pricing seems simple: pay per invocation and duration. But the real costs often come from:

  • Over-provisioned memory (and therefore CPU)
  • Cold starts forcing retry logic
  • Inefficient database connections
  • Unnecessary data transfer

Memory Right-Sizing

The default 128MB is almost never right. But neither is blindly increasing to 1GB.

# Before: 128MB, 2000ms average
def handler(event, context):
    data = process_large_json(event['body'])  # CPU-bound
    return {'statusCode': 200, 'body': json.dumps(data)}

# After: 512MB, 400ms average
# Cost: Actually LOWER due to reduced duration

Use AWS Lambda Power Tuning to find your sweet spot. Often, 512MB or 1024MB is the cost-optimal choice for CPU-bound workloads.

Connection Pooling

Every Lambda invocation creating a new database connection is a recipe for:

  • Slow cold starts
  • Connection exhaustion
  • Unnecessary latency
// Use RDS Proxy or connection pooling
import { Pool } from 'pg';

// Connection reused across warm invocations
const pool = new Pool({
  host: process.env.RDS_PROXY_ENDPOINT,
  max: 1, // Single connection per Lambda instance
});

export const handler = async (event) => {
  const client = await pool.connect();
  try {
    const result = await client.query('SELECT ...');
    return { statusCode: 200, body: JSON.stringify(result.rows) };
  } finally {
    client.release();
  }
};

Provisioned Concurrency (When It Makes Sense)

Provisioned concurrency eliminates cold starts but adds cost. Use it when:

  • Response time SLAs are strict (< 100ms)
  • Traffic is predictable
  • Cold start latency is > 1 second
# Calculate break-even point
# Provisioned: $0.000004463 per GB-second
# On-demand:   $0.0000166667 per GB-second
# If your cold start rate > ~27%, provisioned wins

Quick Wins Checklist

  1. ✓ Right-size memory using Power Tuning
  2. ✓ Use RDS Proxy for database connections
  3. ✓ Enable ARM64 (Graviton2) for 20% cost reduction
  4. ✓ Review CloudWatch logs for timeout patterns
  5. ✓ Use S3 Transfer Acceleration for large payloads

Need Help?

Lambda optimization is one of our specialties. Get in touch if you’re seeing unexpected AWS bills.