DEV Community

Cover image for Streaming S3 Objects in Lambda: Avoiding Memory Exhaustion and Timeouts
Aniket Abhishek Soni
Aniket Abhishek Soni

Posted on AI-assisted

Streaming S3 Objects in Lambda: Avoiding Memory Exhaustion and Timeouts

You ship your data pipeline to production. It passes CI, handles small test files perfectly, and processes records within seconds. Then, a legitimate file arrives that is 5GB in size. Your Lambda function crashes immediately with an OutOfMemory error or hits the 15-minute execution limit, leaving your data state inconsistent and your logs flooded with stack traces.

The core issue is that many developers treat S3 as a file system, calling s3.get_object() and loading the entire payload into local memory. When the file size exceeds your configured Lambda memory, the runtime environment terminates. This article explains how to use byte-range requests to stream large S3 objects into Lambda, allowing you to process files of any size with constant memory usage.

Why this matters: Memory exhaustion in Lambda is a hard failure that triggers retries, potentially leading to duplicate processing if your code isn't idempotent. By streaming data, you decouple your processing capacity from the size of the individual source objects, ensuring your pipeline remains stable regardless of file growth.

flowchart LR
    S3["Amazon S3 (Source)"] --> L["AWS Lambda (Consumer)"]
    L -- "Range: bytes=x-y" --> S3
    L -- "Process Chunk" --> DB[(Destination)]

The contenders

When you need to process large files in Lambda, you are essentially choosing between two architectural patterns: the "Download-and-Process" pattern and the "Stream-and-Process" pattern.

The "Download-and-Process" pattern relies on s3.get_object(), which fetches the entire object into memory. This is simple to implement but scales poorly. The "Stream-and-Process" pattern utilizes the Range parameter in the GetObject API. By requesting specific byte ranges, you pull only the data you need at any given moment, keeping the memory footprint stable even if the file is gigabytes in size.

Memory efficiency

The Download-and-Process approach requires that your Lambda memory configuration is strictly greater than the largest object you expect to process. If your file is 2GB, you must configure a large amount of memory, which increases your cost per invocation. Conversely, streaming keeps your memory usage constant, regardless of the file size. You only need enough memory to hold the buffer for the current chunk being processed.

Operational complexity

Streaming requires more boilerplate. You must manage the state of your read pointer, handle HTTP range requests, and ensure that your logic correctly parses records that might be split across chunk boundaries. The Download-and-Process approach is trivial: load the file, parse the JSON or CSV, and finish. However, this simplicity is a trap; it obscures the inherent scaling limit of the function.

Failure modes

In the Download-and-Process model, a large file failure is usually a hard crash. In the streaming model, the failure mode shifts to network-related issues or malformed chunks. Because you are making multiple requests to S3, you are subject to the standard S3 request limits and potential transient network errors, which requires robust retry logic within your application code.

Feature Download-and-Process Stream-and-Process
Memory usage Scales with file size Constant
Implementation Simple Moderate
Max object size Limited by Lambda RAM Unlimited (within S3 limits)
Throughput High for small files High for large files

Implementing streaming with Boto3

To implement streaming, you use the Range header in the get_object call. You then iterate over the Body stream returned by the SDK.

import boto3

def lambda_handler(event, context):
    s3 = boto3.client('s3')
    bucket = event['bucket']
    key = event['key']

    # Example: Reading in 1MB chunks
    chunk_size = 1024 * 1024
    byte_range = f"bytes=0-{chunk_size-1}"

    response = s3.get_object(Bucket=bucket, Key=key, Range=byte_range)

    # Process the stream
    for chunk in response['Body'].iter_chunks(chunk_size=chunk_size):
        # Your parsing logic here
        # If record is incomplete, buffer until next chunk
        pass
Enter fullscreen mode Exit fullscreen mode

The iter_chunks method (or standard Python file-like object iteration) allows you to process data sequentially. When the end of the range is reached, you calculate the next range and issue another get_object request.

How to measure it yourself

To verify the impact of your changes, you should monitor MaxMemoryUsed via CloudWatch Metrics. Create a test file of 500MB and run your function. If the function is streaming, you should observe that MaxMemoryUsed stays well below your configured limit. If you see the function approaching the limit, your buffer size is likely too large.

You can verify the behavior by checking the logs for REPORT lines, which include the memory usage metrics for every execution. Ensure you are comparing the memory usage of a 5MB file versus a 500MB file; in a streaming architecture, these two executions should have nearly identical memory consumption profiles.

What I'd pick, and why

I recommend the streaming approach for any production data pipeline that ingests files from S3. The "Download-and-Process" method is an anti-pattern for data engineering; it creates a "hidden" limit in your system where your pipeline works fine for months until a larger-than-average file inevitably causes an outage.

While streaming requires more care—specifically around handling record boundaries when a record is split across two chunks—the trade-off is a system that is resilient to data growth. Always ensure that your Range requests align with your data structure (e.g., if you are reading CSVs, aim to break on newline characters) to keep your parsing logic clean.

Clean up

If you created a test bucket and uploaded large files to verify this behavior, ensure you empty and delete the bucket to avoid ongoing storage costs. Use the AWS CLI to remove the objects and then the bucket:

aws s3 rm s3://<your-bucket-name> --recursive
aws s3 rb s3://<your-bucket-name>
Enter fullscreen mode Exit fullscreen mode

References


Tags: #aws #lambda #s3 #dataengineering

About the examples: automated checks confirmed that the Python block parses and that 1 boto3 call matches the AWS service API models (operation and parameter names). The examples have not been run end to end, so test them in a non-production environment before relying on them.

Cover photo by Emile Perron on Unsplash.


This article was drafted with AI assistance and is intended for technical review and fact-checking before publication.

Top comments (0)