DEV Community

Cover image for 7 Serverless Architecture Patterns for Building Scalable Web Apps
Aarav Joshi
Aarav Joshi

Posted on

7 Serverless Architecture Patterns for Building Scalable Web Apps

Serverless architecture has revolutionized the way we build and deploy web applications. As a developer who has worked extensively with this technology, I can attest to its transformative power. In this article, I'll share seven serverless architecture patterns that can help you create scalable web applications.

Function as a Service (FaaS) is the cornerstone of serverless computing. It allows developers to focus solely on writing code without worrying about server management. I've found FaaS particularly useful for building microservices and event-driven architectures. Here's a simple example of an AWS Lambda function in Python:

import json

def lambda_handler(event, context):
    name = event.get('name', 'World')
    return {
        'statusCode': 200,
        'body': json.dumps(f'Hello, {name}!')
    }
Enter fullscreen mode Exit fullscreen mode

This function responds to HTTP requests, greeting the user by name if provided, or with a default greeting otherwise.

The Backend for Frontend (BFF) pattern has been a game-changer in my projects. It involves creating separate backend services for different frontend clients, optimizing data transfer and improving overall performance. Here's how you might structure a BFF using AWS Lambda and API Gateway:

// Mobile BFF
exports.mobileHandler = async (event) => {
    // Logic specific to mobile clients
    return {
        statusCode: 200,
        body: JSON.stringify({ message: 'Mobile-optimized response' })
    };
};

// Web BFF
exports.webHandler = async (event) => {
    // Logic specific to web clients
    return {
        statusCode: 200,
        body: JSON.stringify({ message: 'Web-optimized response' })
    };
};
Enter fullscreen mode Exit fullscreen mode

Event-driven Data Processing is another powerful pattern I've implemented in various projects. It's particularly effective for handling real-time data streams. Consider this Azure Function that processes IoT device data:

public static class IoTDataProcessor
{
    [FunctionName("ProcessIoTData")]
    public static async Task Run(
        [IoTHubTrigger("messages/events", Connection = "IoTHubConnection")] EventData message,
        [CosmosDB(databaseName: "IoTDatabase", collectionName: "DeviceData", ConnectionStringSetting = "CosmosDBConnection")] IAsyncCollector<dynamic> deviceDataOut)
    {
        var dataPoint = new
        {
            DeviceId = message.SystemProperties["iothub-connection-device-id"].ToString(),
            Temperature = message.Properties["temperature"].ToString(),
            Timestamp = DateTime.UtcNow
        };

        await deviceDataOut.AddAsync(dataPoint);
    }
}
Enter fullscreen mode Exit fullscreen mode

This function is triggered by IoT Hub events and stores the processed data in a Cosmos DB collection.

Serverless WebSockets have opened up new possibilities for real-time communication in web applications. I've used this pattern to build chat applications and live dashboards. Here's a basic implementation using AWS API Gateway and Lambda:

const AWS = require('aws-sdk');
const ddb = new AWS.DynamoDB.DocumentClient();

exports.handler = async (event) => {
    const connectionId = event.requestContext.connectionId;
    const routeKey = event.requestContext.routeKey;

    switch (routeKey) {
        case '$connect':
            await ddb.put({
                TableName: 'WebSocketConnections',
                Item: { connectionId: connectionId }
            }).promise();
            break;
        case '$disconnect':
            await ddb.delete({
                TableName: 'WebSocketConnections',
                Key: { connectionId: connectionId }
            }).promise();
            break;
        case 'sendmessage':
            const message = JSON.parse(event.body).message;
            // Broadcast message to all connected clients
            const connections = await ddb.scan({ TableName: 'WebSocketConnections' }).promise();
            const apigwManagementApi = new AWS.ApiGatewayManagementApi({
                apiVersion: '2018-11-29',
                endpoint: event.requestContext.domainName + '/' + event.requestContext.stage
            });
            await Promise.all(connections.Items.map(async ({ connectionId }) => {
                try {
                    await apigwManagementApi.postToConnection({ ConnectionId: connectionId, Data: message }).promise();
                } catch (e) {
                    if (e.statusCode === 410) {
                        await ddb.delete({ TableName: 'WebSocketConnections', Key: { connectionId } }).promise();
                    }
                }
            }));
            break;
    }

    return { statusCode: 200, body: 'Success' };
};
Enter fullscreen mode Exit fullscreen mode

Static Site Generation with Serverless Functions combines the best of both worlds: the performance of static sites with the flexibility of server-side processing. I've used this pattern to create highly performant yet dynamic websites. Here's an example using Netlify Functions:

// netlify/functions/dynamicContent.js
exports.handler = async (event, context) => {
    const userId = event.queryStringParameters.userId;

    // Fetch user-specific data from a database or API
    const userData = await fetchUserData(userId);

    return {
        statusCode: 200,
        body: JSON.stringify(userData)
    };
};

// In your static site's JavaScript
fetch('/.netlify/functions/dynamicContent?userId=123')
    .then(response => response.json())
    .then(data => {
        // Update the page with dynamic content
        document.getElementById('user-content').innerHTML = `Welcome back, ${data.name}!`;
    });
Enter fullscreen mode Exit fullscreen mode

Serverless API Gateways have simplified API management in my projects. They handle routing, authentication, and rate limiting without the need for a dedicated API server. Here's a configuration example for AWS API Gateway:

openapi: 3.0.0
info:
  title: My Serverless API
  version: 1.0.0
paths:
  /users:
    get:
      summary: Get all users
      x-amazon-apigateway-integration:
        uri: arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:123456789012:function:GetUsers/invocations
        passthroughBehavior: when_no_match
        httpMethod: POST
        type: aws_proxy
    post:
      summary: Create a new user
      x-amazon-apigateway-integration:
        uri: arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:123456789012:function:CreateUser/invocations
        passthroughBehavior: when_no_match
        httpMethod: POST
        type: aws_proxy
Enter fullscreen mode Exit fullscreen mode

This configuration defines two endpoints, each integrated with a specific Lambda function.

Lastly, Scheduled Tasks and Cron Jobs have become much more cost-effective with serverless architecture. I've used this pattern for various maintenance tasks and periodic data updates. Here's an example using Google Cloud Functions:

from google.cloud import bigquery

def scheduled_query(event, context):
    client = bigquery.Client()
    query = """
        SELECT DATE(timestamp) as date, COUNT(*) as visit_count
        FROM `my-project.website_analytics.page_views`
        WHERE DATE(timestamp) = DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)
        GROUP BY DATE(timestamp)
    """
    query_job = client.query(query)
    results = query_job.result()

    for row in results:
        print(f"Date: {row['date']}, Visits: {row['visit_count']}")

# Deploy with the following command:
# gcloud functions deploy scheduled_query --runtime python37 --trigger-topic daily-analytics
Enter fullscreen mode Exit fullscreen mode

This function runs a BigQuery job to calculate daily website visits and can be scheduled to run automatically using Cloud Scheduler.

These serverless architecture patterns have significantly improved the scalability and efficiency of web applications I've worked on. They've allowed me to focus on writing business logic rather than managing infrastructure, resulting in faster development cycles and more robust applications.

Serverless computing isn't just a trend; it's a fundamental shift in how we approach web development. By leveraging these patterns, you can create applications that are not only scalable and cost-efficient but also easier to maintain and evolve over time.

As with any technology, it's important to consider the specific needs of your project when deciding which patterns to implement. Serverless architecture offers great flexibility, but it also comes with its own set of challenges, such as cold starts and potential vendor lock-in.

In my experience, the key to success with serverless architecture is to start small, experiment with different patterns, and gradually expand your use as you become more comfortable with the technology. Remember, the goal is to create value for your users, and serverless architecture is a powerful tool to help you achieve that goal more efficiently.

As we continue to push the boundaries of what's possible with web applications, I'm excited to see how serverless architecture will evolve and what new patterns will emerge. The future of web development is serverless, and by mastering these patterns, you'll be well-prepared to build the next generation of scalable, efficient web applications.


101 Books

101 Books is an AI-driven publishing company co-founded by author Aarav Joshi. By leveraging advanced AI technology, we keep our publishing costs incredibly low—some books are priced as low as $4—making quality knowledge accessible to everyone.

Check out our book Golang Clean Code available on Amazon.

Stay tuned for updates and exciting news. When shopping for books, search for Aarav Joshi to find more of our titles. Use the provided link to enjoy special discounts!

Our Creations

Be sure to check out our creations:

Investor Central | Investor Central Spanish | Investor Central German | Smart Living | Epochs & Echoes | Puzzling Mysteries | Hindutva | Elite Dev | JS Schools


We are on Medium

Tech Koala Insights | Epochs & Echoes World | Investor Central Medium | Puzzling Mysteries Medium | Science & Epochs Medium | Modern Hindutva

Top comments (0)