Foundry24 in Denver

How to Lower an AWS Lambda Bill

Robbie aws · lambda · cost-optimization · serverless

Lambda charges per request and per GB-second of duration, so the pricing looks simple. The bill mostly moves with memory settings, database connections and how often a function runs for longer than it needs to. I’d check those in that order.

Memory sizing

The default 128MB is rarely right, and neither is raising everything to 1GB. Lambda allocates CPU in proportion to memory, so CPU-bound code can get cheaper when you give it more.

import json

def handler(event, context):
    data = json.loads(event['body'])  # CPU-bound on a large payload
    return {'statusCode': 200, 'body': json.dumps(data)}

Here is the arithmetic with example timings. They aren’t a benchmark. Say this runs for 2000ms at 128MB and 400ms at 512MB.

MemoryDurationGB-secondsDuration cost per call
128MB2000ms0.25$0.00000417
512MB400ms0.20$0.00000333

The larger size costs less and answers five times faster. That only holds while the work is CPU-bound. A function that spends its time waiting on a database or an API won’t finish any sooner with more memory, so the extra GB-seconds are pure cost.

Don’t guess at the number. AWS Lambda Power Tuning is an open source Step Functions state machine that runs your function at several memory sizes and charts cost against duration.

Connection pooling

A new database connection on every invocation adds latency and can exhaust the database’s connections when traffic spikes. Create the pool outside the handler so warm invocations reuse it.

import { Pool } from 'pg';

// Connection settings other than host come from the PG* environment variables.
const pool = new Pool({
  host: process.env.RDS_PROXY_ENDPOINT,
  max: 1, // Each Lambda instance handles one request at a time
});

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

Reuse only helps within one instance, and a burst of traffic still starts many instances at once. RDS Proxy sits between them and the database and shares a smaller set of connections. It has its own charge, so I’d add it when connection counts are the actual problem.

When provisioned concurrency makes sense

Provisioned concurrency eliminates cold starts but adds cost. It fits predictable traffic with a strict response-time target, say under 100ms, when cold starts take more than a second.

The break-even is a calculation. You pay a lower duration price, plus a charge for every second the capacity is allocated, busy or idle.

# us-east-1, x86, per GB-second
provisioned_allocated = 0.0000041667
provisioned_duration = 0.0000097222
on_demand_duration = 0.0000166667

break_even = provisioned_allocated / (on_demand_duration - provisioned_duration)
print(f"{break_even:.0%}")  # 60%

Provisioned concurrency is cheaper once the allocated capacity is busy more than about 60% of the time. Below that you’re paying to remove cold starts, which can still be the right call. It just isn’t a saving.

Arm

Arm (Graviton2) duration costs 20% less than x86 in us-east-1, at $0.0000133334 per GB-second. Pure Python or Node code usually moves over with a configuration change. Anything with compiled dependencies has to be rebuilt for Arm first.

Timeouts and retries

A function that hangs until its timeout pays for the whole timeout. Asynchronous invocations also retry twice by default after a failure, so a timeout on a slow dependency can bill three times for no result. Set timeouts close to what the function actually needs, and search CloudWatch Logs for Task timed out to find the ones that are hitting them.

Data transfer and logs

Duration isn’t the only line on the bill. A function in a VPC that reaches the internet through a NAT gateway pays that gateway’s per-GB charge. CloudWatch Logs charges for ingestion, so logging full payloads on a busy function adds up. If a function moves a lot of data or logs heavily, look at those lines before tuning memory.

Foundry24 builds and runs software for small businesses

AI agents, automation, and websites, built in a few weeks and then maintained for a monthly fee. If something in your week should be software by now, book a call.

Send a message

It goes to hello@foundry24.io. Replies usually come within a day.