Lambda S3 Trigger Infinite Loop: How Recursive Loop Detection Stops It After About 16 Calls, When It Cannot (DynamoDB, Old SDKs), and the Two-Bucket, Prefix and Guard Fixes
A Lambda S3 trigger loop happens when a function triggered by uploads to a bucket writes its output back into the same bucket: every write is a new upload, which triggers the function again, forever. Lambda now has recursive loop detection, on by default at no charge: when one triggering event has invoked the function about 16 times in a row through S3, SQS, SNS, EventBridge custom buses or direct Lambda-to-Lambda calls, Lambda stops the next invocation and alerts you. The catch, and the reason loops still produce scary bills: detection works only if your function uses a recent AWS SDK, it cannot see loops through DynamoDB or any other service, and the email and Health Dashboard alert can arrive up to 3.5 hours after Lambda stops the loop. Without detection, a loop at 1,000 concurrent copies of a 512 MB function can cost well over $100 an hour, most of it in S3 PUT requests. The fix is to make the loop impossible: write output to a different bucket, or to a prefix the trigger does not watch, and have the code refuse its own output. This page covers stopping a loop in progress, the settings and SDK versions, the cost math, and alarms that catch the loops detection misses.
Jake wanted every photo customers uploaded with a repair booking resized to a thumbnail. Ethan wrote a small function on a Friday: an upload to the bookings bucket triggers it, it makes a thumbnail, and saves it next to the original. On Saturday morning the bucket held 40,000 thumbnails of thumbnails. "Did someone upload 40,000 photos?" Jake asked. "One customer uploaded one photo," Ethan said. "My function did the rest." Lambda had stopped it after about sixteen rounds for each upload, which is why it was 40,000 and not 40 million. This page is how Ethan cleaned it up and made it impossible to happen again.
New to Lambda and S3 triggers? An S3 bucket can send an event notification to a Lambda function whenever an object is created or deleted, so your code runs on every upload without a server waiting for it. S3 invokes the function asynchronously, one event per object, and Lambda runs as many copies in parallel as the events require, up to your account's concurrency. That parallelism is what makes a loop expensive so fast.
Stop a loop that is running right now
If your bucket is filling up or your Lambda invocations graph is a wall, act in this order. Each step takes seconds, and the first one stops new invocations immediately:
- Throttle the function. In the Lambda console, open the function and choose Throttle, then Confirm. This sets its reserved concurrency to 0, so no new invocation can start. From the CLI:
aws lambda put-function-concurrency --function-name thumbnailer --reserved-concurrent-executions 0. - Remove or disable the trigger. For S3, delete the event notification on the bucket (bucket Properties, Event notifications) or remove the trigger under the function's Configuration, Triggers. For SQS and other event source mappings:
aws lambda update-event-source-mapping --uuid MAPPING_UUID --no-enabled(find the UUID withaws lambda list-event-source-mappings --function-name thumbnailer). - Find the defect. Usually the output bucket or prefix in the code is the same as the trigger's source. Look for one variable used for both.
- Clean up what the loop wrote. List the extra objects by their naming pattern and delete them (a lifecycle rule or a batch delete for large numbers), and purge any queue the loop filled.
- Fix the design, then remove the throttle with
aws lambda delete-function-concurrency --function-name thumbnailer, and re-enable the trigger.
Throttling while S3 still has events in flight does not lose them silently: S3 invokes Lambda asynchronously, so throttled events wait in Lambda's async queue and are retried for up to the function's maximum event age (6 hours by default), then dropped or sent to a failure destination if you configured one. Fix the function before you lift the throttle, or the waiting events restart the loop.
How to tell a loop from a genuine traffic spike
A sudden jump in invocations is not always a loop; a marketing email can do the same. Three quick checks tell them apart before you throttle a function your customers need:
- The object names. List the newest objects in the bucket. A loop leaves a pattern: names that grow (
photo-thumb-thumb-thumb.jpg), keys under your output prefix arriving as fast as inputs, or the same object rewritten again and again. Real traffic looks like many different customers' files. - The ratio. Compare uploads from users (your application's own metrics, or S3 PUTs from the upload path) with Lambda invocations. One-to-one is normal; one-to-many is a loop.
- The function's own logs. If the function logs the key it processes, this CloudWatch Logs Insights query shows keys handled more than once in the last hour:
fields @message | filter @message like /processing/ | parse @message "processing * " as key | stats count() as n by key | filter n > 1 | sort n desc. Any key with a count above 1 in a design that should touch each object once is your loop.
Also look at RecursiveInvocationsDropped: if it is above zero, Lambda has already confirmed the loop for you. Ethan's logs showed every customer photo processed sixteen times, each time with a longer name, which settled it in a minute.
Why the function triggers itself
The loop needs three things, and Ethan's thumbnailer had all three:
- A bucket notification on all object-created events (
s3:ObjectCreated:*) with no prefix or suffix filter. - A function that writes an object (the thumbnail) into the same bucket.
- Code that does not check whether the object it was handed is its own output.
Take away any one of the three and the loop cannot happen. That is why the fixes below come in layers: one in the bucket's configuration, one in where the output goes, and one in the code. Using all three is cheap and means a single mistake in one layer is not enough to start a loop. The same shape appears with other services, for example a function triggered by an SQS queue that sends its result back to the same queue, or an SNS subscriber that publishes to its own topic.
The fixes that make the loop impossible
Fix 1: write output to a different bucket. This is the cleanest. Uploads go to jakes-bookings-uploads, thumbnails go to jakes-bookings-thumbnails, and only the first bucket has a notification. The function's role needs s3:GetObject on the first and s3:PutObject on the second, and nothing else. A loop is then impossible even if the code has a bug, because the function cannot write where its trigger listens. As a bonus, the separation makes permissions and lifecycle rules simpler.
Fix 2: separate prefixes with a filtered notification. If you need one bucket, give inputs and outputs different prefixes and filter the notification to the input prefix only:
aws s3api put-bucket-notification-configuration --bucket jakes-bookings \
--notification-configuration '{
"LambdaFunctionConfigurations": [{
"LambdaFunctionArn": "arn:aws:lambda:us-east-1:111122223333:function:thumbnailer",
"Events": ["s3:ObjectCreated:*"],
"Filter": { "Key": { "FilterRules": [
{ "Name": "prefix", "Value": "uploads/" },
{ "Name": "suffix", "Value": ".jpg" }
] } }
}]
}'
The function then writes to thumbnails/, which the notification never sees. Two warnings. This command replaces the bucket's whole notification configuration, so include any other notifications the bucket already has (get them first with get-bucket-notification-configuration). And S3 refuses notification configurations whose prefixes or suffixes overlap for the same event type, so you cannot, for example, have one rule on uploads/ and another on uploads/photos/ for the same events.
Fix 3: a guard in the code. Even with the configuration right, make the function refuse to process its own output. It costs one line and protects you from a later configuration change:
import os, urllib.parse
import boto3
s3 = boto3.client("s3")
OUTPUT_BUCKET = os.environ["OUTPUT_BUCKET"]
OUTPUT_PREFIX = "thumbnails/"
def handler(event, context):
for record in event["Records"]:
bucket = record["s3"]["bucket"]["name"]
key = urllib.parse.unquote_plus(record["s3"]["object"]["key"])
if bucket == OUTPUT_BUCKET and key.startswith(OUTPUT_PREFIX):
print(f"skipping own output {bucket}/{key}")
continue
body = s3.get_object(Bucket=bucket, Key=key)["Body"].read()
thumb = make_thumbnail(body) # your resize code
s3.put_object(Bucket=OUTPUT_BUCKET, Key=OUTPUT_PREFIX + os.path.basename(key),
Body=thumb, Metadata={"generated-by": "thumbnailer"})
Note the unquote_plus: S3 sends object keys URL-encoded in events (a space arrives as +), so compare and use the decoded key. Tagging output with metadata such as generated-by gives you a second check if outputs and inputs ever have to share a prefix, at the cost of one extra HeadObject call per event.
Ethan used all three: a second bucket, a filter on the first, and the guard. "Three locks on one door?" Jake asked. "Three doors," Ethan said. "I only need one of them shut."
The everyday designs that loop (and the ones that look risky but do not)
Most loops come from a handful of ordinary jobs. If yours is in this table, check the right-hand column before you deploy:
| What the function does | Loops? | Why, and the safe version |
|---|---|---|
| Resizes images and saves the result in the same bucket | Yes, without a filter | Every thumbnail is a new object. Second bucket, or a filtered input prefix |
| Converts files (CSV to Parquet, video to MP4) in place | Yes, if the suffix filter matches the output | Filter on the input suffix only (.csv), write to an output prefix |
| Updates an object's metadata by copying it onto itself | Yes, with ObjectCreated:* | A copy is an ObjectCreated:Copy event. Trigger on ObjectCreated:Put only, or use tags instead of metadata |
| Adds tags after a virus or content scan | No, with an ObjectCreated trigger | Tagging sends s3:ObjectTagging:* events, not ObjectCreated. Do not subscribe the function to tagging events |
| Processes access logs and writes a summary into the log bucket | Yes | The summary is a new object in a watched bucket, and S3 may log the write too. Summaries go elsewhere |
| Reads a queue message and re-queues failures to the same queue | Yes, for messages that always fail | Let SQS retry by not deleting the message, with a dead-letter queue on the source queue |
| Writes an audit record to a DynamoDB table whose stream triggers it | Yes, and undetected | Separate audit table, or a stream filter on the event source mapping that excludes the audit items |
The copy-onto-itself case catches experienced developers, because "I only changed the metadata" does not feel like creating an object. To S3 it is one, with a new event, which is why the event type you subscribe to matters as much as the prefix.
Set the filters in Terraform, CloudFormation and SAM
If your infrastructure is code, put the filter there so nobody can "fix" it later by widening the trigger in the console. In Terraform:
resource "aws_s3_bucket_notification" "uploads" {
bucket = aws_s3_bucket.bookings.id
lambda_function {
lambda_function_arn = aws_lambda_function.thumbnailer.arn
events = ["s3:ObjectCreated:Put"]
filter_prefix = "uploads/"
filter_suffix = ".jpg"
}
depends_on = [aws_lambda_permission.allow_s3]
}
resource "aws_lambda_function_recursion_config" "thumbnailer" {
function_name = aws_lambda_function.thumbnailer.function_name
recursive_loop = "Terminate"
}
Terraform's aws_s3_bucket_notification owns the bucket's entire notification configuration, just like the CLI command earlier, so declare every notification for that bucket in one resource. The recursion config resource simply makes the default explicit, which stops anyone from flipping it to Allow without a code review. In AWS SAM, the same filter goes on the function's S3 event:
Thumbnailer:
Type: AWS::Serverless::Function
Properties:
Handler: app.handler
Runtime: python3.13
RecursiveLoop: Terminate
ReservedConcurrentExecutions: 20
Environment:
Variables:
OUTPUT_BUCKET: !Ref ThumbnailBucket
Events:
Upload:
Type: S3
Properties:
Bucket: !Ref UploadBucket
Events: s3:ObjectCreated:Put
Filter:
S3Key:
Rules:
- Name: prefix
Value: uploads/
- Name: suffix
Value: .jpg
In plain CloudFormation the filter sits in the bucket's NotificationConfiguration, under LambdaConfigurations with the same Filter.S3Key.Rules. The bucket needs the function's permission to exist first and the function often needs the bucket name, which is the classic source of a circular dependency; our circular dependency guide shows the S3-to-Lambda way out. A side benefit of the two-bucket design is that the circle disappears, because the function only needs the output bucket's name.
The same guard in Node.js
For functions written in JavaScript, the guard looks the same. The key arrives URL-encoded with spaces as +, so decode it before comparing:
import { S3Client, GetObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3";
const s3 = new S3Client({});
const OUTPUT_BUCKET = process.env.OUTPUT_BUCKET;
const OUTPUT_PREFIX = "thumbnails/";
export const handler = async (event) => {
for (const record of event.Records) {
const bucket = record.s3.bucket.name;
const key = decodeURIComponent(record.s3.object.key.replace(/\+/g, " "));
if (bucket === OUTPUT_BUCKET && key.startsWith(OUTPUT_PREFIX)) {
console.log(`skipping own output ${bucket}/${key}`);
continue;
}
const obj = await s3.send(new GetObjectCommand({ Bucket: bucket, Key: key }));
const thumb = await makeThumbnail(await obj.Body.transformToByteArray());
await s3.send(new PutObjectCommand({
Bucket: OUTPUT_BUCKET, Key: OUTPUT_PREFIX + key.split("/").pop(), Body: thumb,
Metadata: { "generated-by": "thumbnailer" }
}));
}
};
The AWS SDK for JavaScript v3 included in current Node.js runtimes is well above the 3.105.0 minimum for detection. If you bundle your own copy with a bundler, check the version in your lock file.
How Lambda recursive loop detection works
Recursive loop detection is on by default for every account, in all commercial Regions, at no extra charge, and you do not need X-Ray active tracing turned on. Here is what it does:
- When a supported service sends an event to Lambda, the event carries tracing metadata. When your function writes a new event to a supported service with a supported AWS SDK, the SDK updates that metadata, including a count of how many times this chain of events has invoked the function.
- A chain of requests is every invocation caused by the same original event. One customer photo and all the thumbnails of thumbnails it spawns are one chain.
- When a function is invoked approximately 16 times in the same chain, Lambda stops the next invocation in that chain. Other triggers of the same function are not affected, so normal uploads keep working.
- If the function has an on-failure destination or a dead-letter queue, the stopped event is sent there. Make sure that destination is not the resource that triggers the function, or you create a second loop (which detection also stops).
The services it can see: Amazon SQS, Amazon S3, Amazon SNS and Amazon EventBridge custom event buses, plus loops made only of Lambda functions calling each other synchronously or asynchronously. When any other service is part of the loop, detection cannot see it. A function triggered by a DynamoDB stream that writes back to the same table, for example, loops with no automatic stop at all. Our DynamoDB Streams guide covers that trigger; the same three-layer thinking applies (a different table, a filter on the event source mapping, and a guard attribute in the item).
About 16 invocations per chain is a safety net, not a design. In Ethan's case, a few thousand uploads over the night times sixteen rounds each produced the 40,000 objects: annoying, but a cleanup job rather than a bill. For a bucket that receives a million uploads a day, sixteen rounds each is sixteen million extra invocations and sixteen million extra objects before anyone looks.
The SDK versions detection needs
The count only travels if your code writes with a recent enough AWS SDK. Lambda runtimes include an SDK, but if yours bundles an older one in its deployment package or a layer, detection silently stops working. The minimum versions:
| Runtime | Minimum AWS SDK version |
|---|---|
| Python | boto3 1.24.46, botocore 1.27.46 |
| Node.js | 2.1147.0 (SDK v2), 3.105.0 (SDK v3) |
| Java 8 and 11 | 2.17.135 |
| Java 17 | 2.20.81 |
| Java 21 | 2.21.24 |
| .NET | 3.7.293.0 |
| Ruby | 3.134.0 |
| PHP | 3.232.0 |
| Go | V2 SDK 1.57.0 |
To check what a Python function actually runs, log boto3.__version__ and botocore.__version__ at startup, or look at the versions pinned in your requirements.txt and layers. A function that pins boto3==1.20.x for some old reason has no loop protection, and nothing tells you so. Code that writes to S3 with a plain HTTP client or a third-party library instead of the AWS SDK is also invisible to detection.
What a runaway loop costs
The bill from a loop comes from three meters at once. With US East (N. Virginia) prices of October 2026, a function with 512 MB of memory running 200 milliseconds per invocation, writing one object each time, and a loop that has filled the account's default 1,000 concurrency:
| Meter (per hour) | Math | Cost |
|---|---|---|
| Invocations | 1,000 concurrent ÷ 0.2 s = 5,000 per second = 18 million per hour, at $0.20 per million | $3.60 |
| Compute | 18 million × 0.2 s × 0.5 GB = 1.8 million GB-seconds, at $0.0000166667 | $30.00 |
| S3 PUT requests | 18 million PUTs at $0.005 per 1,000 | $90.00 |
| Total | Before storage for the 18 million new objects | about $124 an hour, about $2,970 a day |
The S3 requests, not Lambda, are the biggest line, which surprises people who only watch the Lambda bill. Storage then grows by every object the loop writes, and anything else listening to that bucket (replication, other notifications, analytics) multiplies the cost again. The loop also uses the whole account's concurrency, so your other functions start failing with throttling errors at the same time (our concurrency guide explains that ceiling). These numbers are why the alarms below matter even with detection on: a loop through a service detection cannot see runs at this rate until a person stops it.
Alarms that catch loops, including the ones detection misses
Lambda's own notifications are slow by design: the AWS Health Dashboard entry and the email to the account's primary and alternate operations contacts can take up to 3.5 hours to arrive, and you get at most one email per function per 24 hours. Put your own fast alarms in place:
- Alarm on
RecursiveInvocationsDroppedfor the function (or across all functions). Lambda emits it as soon as it stops a recursive invocation, so it is your earliest signal that detection fired. Any value above 0 is worth a look. - Alarm on
Invocationswell above the function's normal peak, for example three times the busiest hour of the last month. This catches loops through services detection does not cover. - Alarm on
ConcurrentExecutionsnear your account limit, which catches any runaway function before it starves the rest. - Set reserved concurrency on event-driven functions that do not need much. A thumbnailer with reserved concurrency 20 can never use more than 20 copies, which caps both the damage and the bill of any loop.
- Add an AWS Budgets alert and Cost Anomaly Detection. A daily budget for the account (our billing guide sets one up) and anomaly detection on Lambda and S3 spend catch the slow loops that never trip a concurrency alarm.
An example alarm for the first one, sending to an SNS topic you already use for alerts:
aws cloudwatch put-metric-alarm --alarm-name thumbnailer-recursion \
--namespace AWS/Lambda --metric-name RecursiveInvocationsDropped \
--dimensions Name=FunctionName,Value=thumbnailer \
--statistic Sum --period 300 --evaluation-periods 1 \
--threshold 0 --comparison-operator GreaterThanThreshold \
--treat-missing-data notBreaching \
--alarm-actions arn:aws:sns:us-east-1:111122223333:ops-alerts
Make sure the account's operations contact is a mailbox someone reads. Lambda sends its loop emails to the primary contact and the alternate operations contact; if those still point at a former employee, the only warning goes nowhere.
Loops through SQS, SNS and EventBridge
The S3 case is the famous one, but the same pattern appears wherever a function writes to its own trigger:
- SQS: a function processes a message and sends a new message to the same queue (for example to retry or to fan out). Detection stops the chain after about 16 rounds, but note the interaction with the queue: when Lambda stops an invocation, it returns a
RecursiveInvocationExceptionto the event source mapping, which counts as a failed receive. Amazon SQS keeps retrying the message (and Lambda keeps blocking it) until the queue'smaxReceiveCountis reached and the message moves to the source queue's dead-letter queue. Configure that dead-letter queue on the source queue, not on the function; the function's DLQ is for asynchronous invocations only (our SQS DLQ guide shows both). - SNS: a subscriber publishes to the topic it is subscribed to. Use a separate topic for outputs, or a subscription filter policy so the function never receives its own messages. An on-failure destination catches the stopped event.
- EventBridge: a rule on a custom bus triggers a function that puts an event onto the same bus that matches the same rule. Give your function's events a distinct
sourceordetail-typeand exclude it in the rule's pattern; loops on the default event bus are not covered by detection, so this matters even more there. - Lambda to Lambda: function A invokes B, which invokes A. Detection covers this, but a depth counter passed in the payload (stop at a small number) is clearer and catches it on the first round.
What "RecursiveInvocationException" means
When Lambda stops a chain, the caller sees an error rather than a silent drop. For a direct invocation (one function calling another with the SDK), the Invoke call fails with RecursiveInvocationException, HTTP 400, described as "Lambda has detected your function being invoked in a recursive loop with other AWS resources and stopped your function's invocation." For an SQS event source mapping, the same exception goes back to the mapping and counts as a failed receive, as described above. For S3 and SNS, which invoke asynchronously, the event goes to the function's on-failure destination or dead-letter queue if it has one.
If you see this exception in a function you did not think was recursive, treat it as a bug report from AWS: something in the chain writes back to where it came from. The stopped event in your failure destination tells you which object or message started it, which is usually all you need to find the faulty line.
A depth counter for Lambda functions that call each other
For workflows where one function invokes another, a small counter in the payload stops a loop on the very first unexpected round, long before the 16-invocation net:
import json, boto3
lam = boto3.client("lambda")
MAX_DEPTH = 3
def handler(event, context):
depth = int(event.get("depth", 0))
if depth >= MAX_DEPTH:
raise RuntimeError(f"call depth {depth} reached; refusing to continue")
result = do_work(event)
if result.get("next_step"):
lam.invoke(FunctionName=result["next_step"], InvocationType="Event",
Payload=json.dumps({**result, "depth": depth + 1}))
return result
If you find yourself building chains of functions that pass work along, AWS Step Functions is usually the better tool: the workflow and its loops are explicit, every step is visible in the console, and a state machine with a Map state or a counter in its state ends by design instead of relying on a safety net. A self-invoking function that processes a big job in chunks is the classic case where a Step Functions loop is clearer and easier to stop.
Make sure the loop alert reaches a person
Lambda sends its recursive loop emails to the account's primary contact and its alternate operations contact. In many small accounts the operations contact was never set, or points to someone who has left. Check it in the console under your account name, Account, Alternate contacts, or set it from the CLI:
aws account get-alternate-contact --alternate-contact-type OPERATIONS
aws account put-alternate-contact --alternate-contact-type OPERATIONS \
--name "Shop Ops" --title "Operations" \
--email-address ops@example.com --phone-number "+1-555-0100"
A shared mailbox or a distribution list beats one person's inbox. Jake's operations contact turned out to be the address of a shop email account nobody had opened in a year; Ethan changed it the same morning.
When a recursive pattern is intentional: allowing it safely
Some designs recurse on purpose: a function that processes a large job in pieces and re-queues the remainder, or a crawler that queues the links it finds. If detection stops a pattern you designed, you can allow recursion for that one function. In the console, open the function, choose Configuration, Concurrency and recursion detection, then edit Recursive loop detection and choose Allow recursive loops. From the CLI:
aws lambda put-function-recursion-config --function-name chunk-processor --recursive-loop Allow
aws lambda get-function-recursion-config --function-name chunk-processor
# back to the default
aws lambda put-function-recursion-config --function-name chunk-processor --recursive-loop Terminate
The same setting exists in CloudFormation and SAM as the function's RecursiveLoop property (Allow or Terminate). Before you turn it on, build your own brakes, because Lambda's are now off for that function, and RecursiveInvocationsDropped is no longer emitted for it: a depth or remaining-work counter in each message that ends the chain, reserved concurrency to cap the parallelism, and the invocation and budget alarms above. Leave every other function on the default.
Choosing the right S3 events and filters
Many loops start with a notification that is broader than it needs to be. A few choices make the trigger fire only for what you meant:
- Pick the specific event.
s3:ObjectCreated:Putfires for ordinary uploads;s3:ObjectCreated:*also fires for copies, multipart completions and POST uploads. If your function copies objects within the bucket, a*trigger sees its own copies. - Filter by prefix and suffix. Prefix
uploads/and suffix.jpgmeans thumbnails written asthumbnails/x.jpgoruploads/x.webpnever trigger it. - Consider EventBridge for complex rules. With EventBridge notifications turned on for the bucket, you can match on key patterns, object size and more, and exclude your function's own output with an
anything-butpattern on the key prefix. EventBridge events from S3 go to the default bus, though, which detection does not cover, so the guard in your code becomes the main protection.
Our S3 event not triggering Lambda guide covers the opposite problem, filters so tight that nothing fires, and how to test them.
Find risky triggers across your account
Loops are easier to prevent than to find after the fact, so it is worth a one-time sweep of the account. This boto3 script lists every bucket that sends events straight to a Lambda function and flags notifications with no prefix or suffix filter, the configuration every S3 loop starts from:
import boto3
from botocore.exceptions import ClientError
s3 = boto3.client("s3")
for b in s3.list_buckets()["Buckets"]:
name = b["Name"]
try:
conf = s3.get_bucket_notification_configuration(Bucket=name)
except ClientError as e:
print(f"{name}: cannot read ({e.response['Error']['Code']})"); continue
for c in conf.get("LambdaFunctionConfigurations", []):
rules = c.get("Filter", {}).get("Key", {}).get("FilterRules", [])
fn = c["LambdaFunctionArn"].split(":")[-1]
flag = "NO FILTER" if not rules else ", ".join(f"{r['Name']}={r['Value']}" for r in rules)
print(f"{name} -> {fn} events={','.join(c['Events'])} {flag}")
For every line marked NO FILTER, open the function and check where it writes. If it writes anywhere in that bucket, you have found a loop waiting to happen. Buckets in other Regions may need a client for that Region, and the caller needs s3:ListAllMyBuckets and s3:GetBucketNotification.
The other half is the SDK. A function that logs its SDK version on startup makes the check trivial during a review:
import boto3, botocore
print(f"boto3 {boto3.__version__} botocore {botocore.__version__}") # needs 1.24.46 / 1.27.46+ for loop detection
Run the sweep again whenever someone adds a trigger in the console rather than in code; console changes are the ones that skip review.
Test a new trigger without risking a loop
The safest moment to find a loop is before production traffic reaches it. A five-minute routine for any new event-driven function:
- Deploy to a test bucket with the same notification and filter as production.
- Set reserved concurrency to 1 while testing:
aws lambda put-function-concurrency --function-name thumbnailer --reserved-concurrent-executions 1. Even a loop then runs one copy at a time. - Upload exactly one file:
aws s3 cp test.jpg s3://jakes-bookings-test/uploads/test.jpg. - Count the invocations after a minute. In CloudWatch Logs Insights, on the function's log group:
filter @type = "REPORT" | stats count() as invocations. One upload should mean one invocation; two or more means something is re-triggering it. - List what the function wrote and confirm it landed outside the watched prefix or in the output bucket.
- Raise the concurrency to the production value only after the count is right.
It also helps to know your ceiling. aws lambda get-account-settings --query "AccountLimit.ConcurrentExecutions" shows the account's concurrency limit in the Region; that number is how many copies a loop could reach if the function has no reserved concurrency of its own.
Cleaning up after a loop
When the loop is stopped and fixed, there is usually debris. Clear it methodically:
- Count the damage before deleting anything:
aws s3 ls s3://jakes-bookings/thumbnails/ --recursive --summarize | tail -2shows how many objects and how much data the loop left. - Delete by pattern. For a few thousand objects,
aws s3 rm s3://jakes-bookings/thumbnails/ --recursive --exclude "*" --include "*thumb-thumb*"(adjust to your naming). For millions, a temporary lifecycle rule that expires the prefix after one day is cheaper and needs no scripting; S3 lifecycle expiration requests are not charged. - Check versioning. If the bucket is versioned, deleting creates delete markers and the old versions still cost money; add a lifecycle rule for noncurrent versions too.
- Purge queues and failure destinations the loop filled, after you have copied anything you need for the investigation.
- Look at the bill a day later. The request and compute charges have already happened; if they are large and the loop was an honest mistake, AWS Support can be asked to review it.
Recursive loop problems, by symptom
The bucket fills with copies of copies
The function writes to the prefix or bucket its trigger watches. Throttle it, then move output to another bucket or an unwatched prefix and add a guard in the code.
Lambda did not stop the loop
The loop passes through a service detection cannot see (DynamoDB, the default EventBridge bus, any other service), the function uses an SDK older than the minimums, it writes without the AWS SDK, or recursion is set to Allow. Throttle the function and fix the design.
I got the "recursive loop" email hours after it started
Notifications can take up to 3.5 hours. Alarm on RecursiveInvocationsDropped and on invocations so you hear about it within minutes.
My intentional recursive job stops after about 16 rounds
Detection is doing its job. Allow recursive loops for that one function, and add a depth counter, reserved concurrency and alarms first.
SQS messages keep coming back after the loop was stopped
Each stopped invocation counts as a failed receive, so SQS retries until maxReceiveCount. Let the messages reach the source queue's dead-letter queue, or purge the queue once the bug is fixed.
Other functions are throttled while the loop runs
The loop is using the account's concurrency. Throttle the looping function, and give event-driven functions reserved concurrency so one cannot starve the rest.
The notification configuration is rejected as ambiguous
Two rules for the same event type have overlapping prefixes or suffixes. Use non-overlapping prefixes, or one rule with a broader filter and a check in the code.
The loop restarted as soon as I removed the throttle
Throttled S3 events were waiting in Lambda's asynchronous queue and were retried. Deploy the fixed code or filter first, then remove the throttle; or lower the function's maximum event age so stale events are dropped.
Invocations doubled after I added a second notification
Two notification rules, or a notification plus an EventBridge rule, both invoke the function for the same object. Keep one path per event.
The guard in my code never matches
The key in the event is URL-encoded. Decode it with urllib.parse.unquote_plus (or decodeURIComponent after replacing + in Node.js) before comparing.
Lambda recursive loops: frequently asked questions
What is Lambda recursive loop detection?
A default Lambda feature that tracks how many times one event chain invokes a function through supported services. After about 16 invocations, Lambda stops the next one and notifies you.
How do I stop a Lambda function from triggering itself?
Write its output to a different bucket or queue than the one that triggers it, filter the trigger to input objects only, and add a check in the code that skips its own output.
Does Lambda recursive loop detection work with S3?
Yes. It covers loops through Amazon S3, SQS, SNS and EventBridge custom event buses, and loops between Lambda functions, as long as the function uses a supported AWS SDK version.
Does recursive loop detection work with DynamoDB?
No. Loops that include DynamoDB or other unsupported services are not detected, so use guards in your code, reserved concurrency and alarms.
How many times can a Lambda function loop before it is stopped?
About 16 invocations in the same chain of requests. Invocations from other triggers of the same function are not affected.
Does recursive loop detection cost anything?
No. It is on by default for all accounts at no charge, and it does not require X-Ray active tracing.
How do I turn off recursive loop detection for a function?
Set Recursive loop detection to Allow recursive loops in the function's Concurrency and recursion detection settings, or run aws lambda put-function-recursion-config with --recursive-loop Allow.
How will I know Lambda stopped a recursive loop?
The RecursiveInvocationsDropped metric rises immediately, and an AWS Health Dashboard entry and email follow within about 3.5 hours, at most one email per function per day.
How do I stop a Lambda loop that is running now?
Choose Throttle on the function (reserved concurrency 0), then remove or disable its trigger. Fix the code or configuration before you remove the throttle.
How much can a Lambda S3 loop cost?
At 1,000 concurrent copies of a 512 MB, 200 ms function, about $124 an hour in us-east-1, most of it S3 PUT requests, before storage. Detection, reserved concurrency and alarms keep it far lower.
Why is my S3 trigger firing for files my function created?
The notification covers the prefix or suffix your function writes to, or uses s3:ObjectCreated:* while your function copies objects. Narrow the filter and write output elsewhere.
Should I use two buckets or prefixes to avoid S3 loops?
Two buckets is the most robust because the function cannot write where its trigger listens. Prefixes with a filtered notification work when one bucket is required.
Which SDK version does recursive loop detection need for Python?
boto3 1.24.46 and botocore 1.27.46 or later. Functions that bundle an older boto3 have no loop protection.
Can an SQS dead-letter queue cause a Lambda loop?
Yes, if the dead-letter queue or on-failure destination is also the function's trigger. Point failures at a separate queue that nothing invokes the function from.
What is the RecursiveInvocationsDropped metric?
A CloudWatch metric in the AWS/Lambda namespace counting invocations Lambda stopped because a chain passed about 16 invocations. It is not emitted for functions set to allow recursion.
Does reserved concurrency prevent Lambda loops?
It does not prevent them, but it caps how many copies can run at once, which limits the damage and the cost while the loop lasts.
For readers preparing for an AWS certification
We have been covering AWS certifications alongside our fixes, so here is a short extra for readers studying for one. If you only came for the fix, you already have it; feel free to skip this part.
Exams that test this topic: Developer – Associate (DVA-C03 from December 1, 2026) • CloudOps Engineer – Associate (SOA-C03) • Solutions Architect – Associate (SAA-C03).
Here are the exam-style questions this topic tends to raise, with the reasoning you need to answer them:
1. A Lambda function triggered by uploads to a bucket writes processed files back to the same bucket, and invocations grow without end. What is the best fix?
Write the output to a different bucket (or a prefix the notification does not include) and filter the trigger to the input prefix or suffix.
2. What does Lambda do by default when one event invokes a function about 16 times through SQS, SNS, S3 or EventBridge?
Recursive loop detection stops the next invocation in that chain, emits RecursiveInvocationsDropped and notifies the account contacts.
3. A loop runs through a DynamoDB stream and the function writes back to the same table. Will Lambda stop it?
No; loops through DynamoDB are not detected, so use a separate table, an event filter, reserved concurrency and alarms.
4. A runaway function must be stopped immediately without deleting it. What do you do?
Set its reserved concurrency to 0 (Throttle), then remove or disable the trigger before fixing the code.
5. Which CloudWatch metric shows that Lambda stopped a recursive loop?
RecursiveInvocationsDropped in the AWS/Lambda namespace.
6. How can you limit the damage any single event-driven function can do to the account's concurrency?
Configure reserved concurrency on the function so it can never use more than that many concurrent executions.
Exam codes and dates change often. Our AWS certification changes page keeps track of what is current.
By Saturday lunchtime the 40,000 extra thumbnails were scheduled for deletion by a one-day lifecycle rule, the thumbnailer wrote to its own bucket, and an alarm on RecursiveInvocationsDropped pointed at Ethan's phone. Jake asked what would have happened without Lambda's built-in stop. Ethan showed him the cost table. "Then I am glad it counts to sixteen," Jake said. "Count to zero next time," Ethan said. "That is what the second bucket is for."
📌 If you keep one line from this page
Never let a function write where its trigger listens: use a second bucket (or a filtered prefix) and a guard in the code, throttle first if a loop is running, and alarm on RecursiveInvocationsDropped and invocations because detection only covers S3, SQS, SNS, EventBridge and Lambda with recent SDKs.
Stops after ~16 invocations per chain · alerts up to 3.5 h late · ~$124/hour runaway example (us-east-1) · DynamoDB loops not detected.
Revision note. Written October 22, 2026, with Lambda's recursive loop detection behavior and US East (N. Virginia) Lambda and S3 prices of that date. "An ounce of prevention is worth a pound of cure," the proverb says; with event triggers, the ounce is a second bucket.