
Overview of Serverless Architecture
Get an Overview of Serverless Architecture and learn how it simplifies app deployment, scales automatically, and reduces server management for developers.
What Is Serverless Architecture?
🡺
In a traditional setup, developers need to take care of everything, from writing code to setting up servers, making sure they’re running properly, and upgrading them when needed.
In a serverless setup, all that server work is handled by a cloud provider like:
- • Amazon Web Services (AWS)
- • Microsoft Azure
- • Google Cloud
As a developer, you just write your code in small chunks called functions, and the cloud provider runs them for you whenever needed.
For example, you might write a small function to handle a payment on your website. That function will only run when someone actually makes a payment.
How Does Serverless Work?
🡺
Here’s a simple way to understand it:
- • You write some code and upload it to a cloud service like AWS Lambda or Google Cloud Functions.
- • The cloud waits for something to happen, like someone clicking a button on your website or uploading a file.
- • When that event happens, the cloud automatically runs your code, finishes the task, and shuts everything down when done.
- • You only pay for the time your code is running—no need to pay for idle servers.
Some common types of events that can trigger your code include:
- • A user visiting your website
- • A new file is being uploaded
- • A new database entry
- • A scheduled time (like a daily report)
Main Parts of Serverless Architecture:
To keep things simple, think of serverless as being made up of four basic parts:
- 1. Functions (Code): Small bits of code that do a specific job.
- 2. Triggers: Something that makes the function run (like a button click).
- 3. APIs: A way for different parts of the app to talk to each other.
- 4. Managed Services: Cloud tools that handle things like databases, files, or user logins.
Benefits of Using Serverless:
- 1. No Server Headaches: You don’t need to set up or manage any servers. The cloud provider handles all of that.
- 2. Scales on Its Own: If your app suddenly becomes popular and gets thousands of users, the cloud will automatically handle the extra traffic—no need for you to do anything.
- 3. Pay Only When Used: You only pay when your code is actually doing something. If nobody is using your app, you don’t pay.
- 4. Faster Development: Since you don’t worry about infrastructure, you can focus only on writing the actual app features. That makes development quicker.
- 5. More Reliable: Cloud platforms automatically handle backups and fix many issues behind the scenes, so your app is less likely to crash.
When Should You Use Serverless?
Serverless is great for many use cases, especially when:
- • You need to build a quick web or mobile backend
- • Your app doesn’t run all the time (e.g., only when someone visits your site)
- • You need to process files like images or videos
- • You want to send automatic emails or notifications
- • You’re working on a start-up and want to keep costs low
Popular Tools to Build Serverless Apps:
- 1. Serverless Framework: Helps deploy and manage your serverless code.
- 2. AWS SAM: A tool from Amazon to manage AWS serverless projects
- 3. Netlify Functions: Easy to use for websites and simple apps.
- 4. Firebase Cloud Functions: Popular for mobile and web apps.
Terraform: Let's you set up cloud resources using code.
Explore Other Demanding Courses
No courses available for the selected domain.
Real-Time Example: A Serverless Image Upload App:
Let’s say you want to create a simple web app where users can upload images, and the app automatically resizes them before saving.
Here’s how you can build this with serverless architecture:
Tools Used:
- • Frontend: A basic webpage (HTML + JavaScript)
- • Backend: AWS Lambda (to process the images)
- • Trigger: AWS S3 (to store uploaded images and trigger the function)
- • Other Services: Amazon API Gateway (to handle HTTP requests)
How It Works:
- 1. A user visits your website and uploads a photo.
- 2. The image gets stored in an S3 bucket (Amazon’s cloud storage).
- 3. When the upload finishes, it triggers a Lambda function.
- 4. The Lambda function resizes the image and stores the new version in a separate folder.
- 5. The user gets a link to download the resized image.
Why Serverless Is a Good Fit:
- • You don’t need to run servers 24/7.
- • You only pay when someone uploads an image.
- • The app can handle one user or a million users—AWS automatically adjusts resources.
- • It’s fast to build and easy to update.
Step-by-Step Guide:
Step 1: Create Two S3 Buckets or Folders
- 1. Go to the AWS S3 console.
- 2. Create a bucket named, for example: my-image-upload-app
- 3. Inside the bucket, create two folders:
- • uploads/ – where raw images go
- • resized/ – where resized images will be saved
- 4. Enable event notification on the uploads/ folder:
- • Go to Properties > Event Notifications
- • Set up an event to trigger on PUT (upload) events
- • Choose Lambda Function as the destination (you'll connect it after creating the Lambda)
Step 2: Create the AWS Lambda Function
💻 Option 1: Use AWS Console
- 1. Go to AWS Lambda > Create Function
- 2. Choose "Author from scratch"
- 3. Name it: resizeImageFunction
- 4. Set Runtime: Python 3.x or Node.js (example below uses Node.js)
- 5. Under Permissions, choose “Create a new role with basic Lambda permissions”
Sample Code (Node.js with Sharp image library)
Install dependencies:
npm install sharp
zip -r function.zip .
index.js:
const AWS = require('aws-sdk');
const S3 = new AWS.S3();
const Sharp = require('sharp');
exports.handler = async (event) => {
const bucket = event.Records[0].s3.bucket.name;
const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
try {
// Get original image
const originalImage = await S3.getObject({ Bucket: bucket, Key: key }).promise();
// Resize the image using Sharp
const resizedImage = await Sharp(originalImage.Body)
.resize(300, 300)
.toBuffer();
const newKey = key.replace('uploads/', 'resized/');
// Upload resized image
await S3.putObject({
Bucket: bucket,
Key: newKey,
Body: resizedImage,
ContentType: 'image/jpeg',
}).promise();
console.log('Image resized and uploaded successfully');
return { statusCode: 200, body: 'Success' };
} catch (err) {
console.error(err);
return { statusCode: 500, body: 'Error resizing image' };
}
};
Step 3: Connect Lambda to S3 Trigger
- Go back to your S3 bucket > Properties > Event Notifications
- Edit or create a new notification:
- Trigger on PUT
- Prefix: uploads/
- Select the Lambda function you created
Step 4: Create the Web Frontend (HTML + JS)
Create a basic HTML form:
<!DOCTYPE html>
<html>
<head>
<title>Image Upload</title>
</head>
<body>
<h2>Upload an Image</h2>
<input type="file" id="fileInput" />
<button onclick="uploadImage()">Upload</button>
<p id="message"></p>
<script>
async function uploadImage() {
const file = document.getElementById('fileInput').files[0];
const fileName = `uploads/${file.name}`;
const response = await fetch('https://<your-api-gateway-endpoint>/upload', {
method: 'PUT',
headers: {
'Content-Type': file.type
},
body: file
});
if (response.ok) {
document.getElementById('message').innerText = 'Image uploaded. Processing...';
} else {
document.getElementById('message').innerText = 'Upload failed.';
}
}
</script>
</body>
</html>
Step 5: Set Up API Gateway (Optional)
If you want users to upload images securely using a signed URL:
- Create an API Gateway REST API.
- Create a POST method that triggers a Lambda function.
- This Lambda returns a pre-signed S3 URL that your frontend can use to upload.
Here’s a simple Lambda for generating a signed URL:
const AWS = require('aws-sdk');
const s3 = new AWS.S3();
exports.handler = async (event) => {
const bucket = 'my-image-upload-app';
const key = `uploads/${event.queryStringParameters.filename}`;
const params = {
Bucket: bucket,
Key: key,
Expires: 60, // 1 minute
ContentType: 'image/jpeg'
};
const uploadURL = await s3.getSignedUrlPromise('putObject', params);
return {
statusCode: 200,
body: JSON.stringify({ uploadURL })
};
};
Step 6: Test the Workflow
- Open your HTML page in a browser.
- Select an image and click Upload.
- Check your S3 bucket: the image should appear in the uploads/ folder.
- After a few seconds, the resized image should appear in the resized/ folder.
- You can share the S3 public link to the resized image (if the bucket/folder is public or you generate a signed URL).
Final Conclusion:
Serverless architecture is changing how modern applications are built. It takes away the stress of managing servers and allows developers to focus more on building features. Whether you're a solo developer, start-up founder, or part of a large company, going serverless can help you move faster, save money, and create scalable applications.
Do visit our channel to know more: SevenMentor