Cloud Bills: How One Loop Cost Someone Real Money

In June 2022, a developer deployed a small change to a serverless app and accidentally made a function call itself. Recursively. With a 30-second timeout, on CloudFront, at every point of presence. He went to bed. His billing alert, set at $300 against a usual bill of $200 a month, fired the next morning at $1,484 already spent. He removed the function and redeployed within 30 minutes of waking, but the loop had run all night, and because CloudFront executes at every point of presence, the charges came from all of them. The settled bill: $4,600 (his writeup). And an ending most retellings skip: after two weeks of uncertainty, AWS refunded the money as a one-time favor (his follow-up). He earned it the slow way, by documenting everything. His advice for the day it happens to you: acknowledge the honest mistake, fix it fast, show how you will prevent a repeat, and answer support the day they write.
One line of code, one night, four months of rent. This post is about why that keeps happening and the three defenses that stop it.
Why did my cloud bill spike?
Every cloud service charges for a unit of work. Serverless functions charge per invocation and per gigabyte-second of compute. CDNs charge per gigabyte of bandwidth. AI APIs charge per token. Storage charges per gigabyte kept and per gigabyte served.
The trap is that the meter is invisible while you build. Your code does not feel different when it runs once or a million times. And AI assistants write exactly the patterns that multiply meters: retry loops with no limit, polling every second, a function that calls another function that calls the first. Each is harmless in a demo with three users. With real traffic, or one bug, the multiplication never stops.
The $4,600 story has a second lesson hidden in it: his billing alert did fire, hours late, because usage data takes time to collect. In his case the charges took up to 24 hours to appear and 48 to finalize, and CloudFront, which gathers usage from every point of presence, is the slowest kind. An alert is a smoke detector, not a sprinkler. You want both.
Defense 1: a budget that does something, not just says something
Every major platform has budget alerts, and setting one is the single highest-value ten minutes in this post. On AWS that is Budgets; on Vercel it is Spend Management, which can notify, fire a webhook, or pause your deployments at a limit.
Two details matter:
- A notification alone does not stop the meter. Vercel’s docs say it plainly: setting a budget does not stop usage; you have to turn on the pause. On AWS, a budget can act on its own: Budget Actions can apply an IAM policy or a service control policy when a threshold hits. And for a runaway Lambda function specifically, the kill switch is setting its reserved concurrency to 0, which throttles every new invocation (Lambda concurrency docs). An email you read tomorrow morning is the $1,484 lesson.
- Set the number near your reality, not your dreams. If your app costs $20 a month, alert at $50 and act at $100. An alert at $5,000 is a pager that only rings when it is too late.
Defense 2: caps in the code, because alerts are late
Billing data lags by hours. Code is instant. So the code itself needs limits on anything that can multiply:
- Retries get a maximum attempt count, then a clear error for the user. “Retry until it works” is how one failing provider becomes a thousand paid calls from one click.
- Loops and recursion get an explicit bound. If a function can invoke itself or fan out, put a depth or iteration limit in the code, not in your head.
- Polling gets a slow interval and a stop condition. “Check every second forever” is a bill; “check every 30 seconds until done, give up after 10 minutes” is a feature.
This is the same habit as rate limiting from the launch checklist: anything that can be triggered repeatedly, by users or by your own code, gets a ceiling.
If your functions run on AWS, one net already exists: Lambda’s recursive loop detection is on by default and stops loops that pass through SQS, S3, SNS, or EventBridge (Lambda docs). It would not have caught the 2022 story, because Lambda@Edge calling itself through CloudFront is not covered, and it does not see retry loops inside your own code. The caps above are still yours to set.
Defense 3: name the meter before it names you
For every service your app touches, find the pricing page and answer one question: what is the unit? Invocation, gigabyte-second, gigabyte of bandwidth, token, row read, email sent. Write the answers somewhere you will see them. Most surprise bills are not exotic; they are a unit nobody knew was metered, multiplied by a loop nobody capped. Bandwidth is the classic one for media apps, and AI tokens are the classic one for AI features.
Prove it with two runnable tests
Save this as test_cost_guard.py in an empty folder and run python3 test_cost_guard.py. It rebuilds the retry-forever bug in miniature, standard library only: a user action that calls a failing provider, once with no cap, once with a maximum and a clear error.
import unittest
MAX_CALLS_PER_ACTION = 5calls = []
class UserFacingError(Exception): pass
def flaky_api(payload): calls.append(payload) raise RuntimeError("provider down")
def process_retry_forever(payload): for _ in range(1000): # "retry until it works" try: return flaky_api(payload) except RuntimeError: continue raise RuntimeError("provider down")
def process_guarded(payload, max_attempts=3): for attempt in range(max_attempts): try: return flaky_api(payload) except RuntimeError: if attempt == max_attempts - 1: raise UserFacingError( "we could not reach the provider; try again in a few minutes" )
# Which version the app uses. FIX (after the first run): point it at process_guarded.process = process_retry_forever
class CostGuardTests(unittest.TestCase): def setUp(self): calls.clear()
def test_one_user_action_does_not_run_away(self): with self.assertRaises(Exception): process("job-1") self.assertLessEqual( len(calls), MAX_CALLS_PER_ACTION, f"one action made {len(calls)} provider calls", )
def test_the_user_gets_a_clear_error(self): with self.assertRaises(UserFacingError): process("job-1")
if __name__ == "__main__": unittest.main()The first run fails the way your bank account would:
FAIL: test_one_user_action_does_not_run_away (__main__.CostGuardTests)AssertionError: 1000 not less than or equal to 5 : one action made 1000 provider calls
Ran 2 tests in 0.001sFAILED (failures=1, errors=1)One user action made a thousand paid calls, and the user got a raw crash at the end of it. Flip the one marked line to process_guarded and run again:
Ran 2 tests in 0.000sOKSame failing provider, three calls, a clear message. The tests pin behaviors a person experiences (one click stays cheap; a failure reads like a sentence, not a stack trace), not how the code achieves them, so a later refactor that breaks either one fails here first. They protect these two behaviors only; the budget alert from defense 1 protects everything they cannot see.
The hand check: ten minutes, three tabs
Do this tonight. Tab one: your host’s billing page, set the budget and the automatic action. Tab two: your database and AI provider’s billing pages, same thing. Tab three: each pricing page, and write down the metered unit. If any tab takes more than ten minutes, that is the provider to watch.
The prompt to paste
Audit this app for runaway-cost patterns. Find every loop, retry, recursion, poll or fan-out that touches a paid service (functions, bandwidth, AI tokens, emails). For each: what stops it, and what is the worst-case cost of one trigger? Then list which services have budget alerts or hard caps configured. Do not change code yet.
Surprise bills are one of the things that break when your app meets real users, and the fix is an evening, not an incident.
The Get AI Native ebook goes deeper on this. It is free, and the expected launch is around Christmas. Join the waitlist on the homepage.