Serverless Word Counter with AWS Lambda & S3 | Day 3 Project
Built an event-driven text pipeline using Amazon S3 & Python Lambda for Day 3 of AWS Gujarat Students Builder Week 2026. See the full serverless setup here.
Building an Event-Driven Serverless Word Counter with AWS Lambda and Amazon S3
1. Introduction & Background
As part of the ongoing AWS Gujarat Students Builder Week 2026, student developers and cloud enthusiasts across the region are diving deep into hands-on cloud native patterns. Following the foundational systems architectures introduced during Day 1 and Day 2 by industry community champions, Day 3 challenged us to build a real-world file-processing pipeline.
The objective of this mini-project was to transition from managing static infrastructure to architecting a functional, automated, serverless utility: a Word Counter that instantly processes raw text files the moment they are uploaded to storage, calculates text analytics, and stores finalized data back into an isolated bucket directory.
2. Architecture Overview
The pipeline relies completely on an Event-Driven Architecture (EDA). Rather than provisioning virtual server instances that idle and accumulate costs continuously, compute resources are allocated dynamically on-demand:
- Amazon S3 (Storage Tier): Handles incoming raw files and segregates processing output summaries.
- S3 Event Notification (Trigger Tier): Monitors a localized bucket route and automatically invokes computational paths when conditions match.
- AWS Lambda (Compute Tier): A serverless Python 3.12 microservice that executes calculation logic instantly on invocation and drops back down to zero footprint.
3. Step-by-Step Implementation
Step 1: Storage Segregation in Amazon S3
I created a globally unique S3 bucket named
pratham-word-counter-2026 hosted in the Asia Pacific (Mumbai) ap-south-1 region. To prevent accidental processing loops (where an output file inadvertently triggers another execution cycle), I explicitly isolated data streams by nesting two distinct folders inside the bucket root:-
uploads/(Target directory for raw incoming text documents)
-
results/(Target directory for structured processing metrics)
Step 2: Microservice Construction & Identity Management
Using the AWS Lambda dashboard, I initialized a function called
WordCounter running on a Python 3.12 runtime. By default, Lambda functions operate under a secure zero-trust condition and lack authority to communicate with outer services like S3.To safely bridge this gap, I navigated to AWS IAM (Identity and Access Management), opened the automatically generated execution role, and attached the
AmazonS3FullAccess managed policy. This provided our function with read-and-write permissions for our bucket objects.Step 3: Configuring the Event-Driven Trigger
I added an S3 Event Trigger directly to the Lambda function diagram overview. To keep our function highly performant and secure, I filtered incoming events using precise parameters:
- Prefix Filter:
uploads/
- Suffix Filter:
.txt
This rule ensures that the function executes only if a text document lands inside the designated folder, leaving all other paths completely untouched.

Step 4: Writing the Pipeline Logic
I wrote a Python handler utilizing the
boto3 SDK to pull the target object metadata, decode the raw binary byte stream into utf-8 strings, and run string manipulation splits to extract line and word metrics.Here is the exact code block running on my Lambda cluster :- (Scroll Down for code)
---
Testing and Verification Results
To test the automation pipeline, I uploaded a local text file named
Pratham Gediya.txt into the uploads/ folder containing the following text lines:Pratham Gediya AWS Gujarat Students Builder Week 2026 Day - 3 | 1st Mini Project By Me.
Within milliseconds of the upload completing, the event trigger fired, Lambda executed, and successfully dropped a structured metric summary to
results/Pratham Gediya.txt_result.txt completely on its own :---
File: uploads/Pratham Gediya.txt
Total Lines: 3
Total Words: 17
---


---

---
Key Takeaways & Lessons Learned
- The Efficiency of Serverless Compute: I witnessed how scaling operates when compute resources only exist during processing execution lifecycles, dropping infrastructure costs to absolute zero when idle.
- Infrastructure Governance: Configuring IAM properties firsthand emphasized why configuring granular permissions is critical in enterprise cloud ecosystems to prevent unauthorized access.
- Loop Mitigation Strategy: Designing separate entry and exit directory pathways highlighted the structural adjustments needed to keep serverless functions from triggering infinite execution feedback loops.
A massive thank you to @ Tejasvi Shekhat and all the AWS Student Builder Group Leaders of Gujarat for coordinating this incredible virtual learning series and empowering student builders with practical cloud foundations!
import boto3
import urllib.parse
# Initialize the S3 client
s3 = boto3.client('s3')
def lambda_handler(event, context):
# 1. Get the bucket name and the file name from the trigger event
bucket = event['Records'][0]['s3']['bucket']['name']
key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8')
try:
# 2. Download the file from S3
response = s3.get_object(Bucket=bucket, Key=key)
text_content = response['Body'].read().decode('utf-8')
# 3. Count lines and words
lines = text_content.split('\n')
words = text_content.split()
line_count = len(lines)
word_count = len(words)
# 4. Format the result text
result_text = f"File: {key}\nTotal Lines: {line_count}\nTotal Words: {word_count}"
# 5. Create the new file name in the results folder
file_name_only = key.split('/')[-1]
result_key = f"results/{file_name_only}_result.txt"
# 6. Upload the result text file back to S3
s3.put_object(Bucket=bucket, Key=result_key, Body=result_text)
print(f"Successfully saved to {result_key}")
return {'statusCode': 200, 'body': 'Word count successful!'}
except Exception as e:
print(f"Error: {str(e)}")
return {'statusCode': 500, 'body': 'Error processing file.'}Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article