Serverless Applications

Serverless is an approach to cloud application development in which developers focus on writing individual functions that run in response to specific events. These functions are ephemeral and scale automatically with demand, without the need to manage the infrastructure. This approach lets developers set server administration aside and focus on application logic, offering greater agility, automatic scaling, and lower costs by paying only for function execution time.
The promise of greater agility, automatic scaling, and lower costs in serverless architecture depends on the context and specific use case. While serverless can provide these benefits in many scenarios, it is important to consider whether the architecture suits each application's particular needs and characteristics.
In some cases, adopting serverless architecture can lead to higher costs if it is not planned and optimized properly. For example, if an application has a constant, predictable workload, traditional infrastructure may be more cost-effective than serverless functions, where you pay for each invocation and execution time.
It is therefore essential to evaluate the context and use case carefully before deciding to adopt serverless architecture. Factors to consider include variability in demand, the nature of the application, operating costs, and performance needs. This helps determine whether serverless really makes sense in that particular context and will provide greater agility, automatic scaling, and lower costs.
Key components
For all these examples, I will use the Serverless Framework and AWS.
The truth about server-"less" is that there are indeed servers. For those, we need cloud service providers such as AWS Lambda, Azure Functions, and Google Cloud Functions. These providers handle infrastructure management, automatic scaling, security, and monitoring, allowing developers to focus on application logic.
In addition to the cloud providers above, there are more specialized providers offering specific services for serverless architecture, such as Supabase (database services and other Firebase-style utilities) and Vercel (deployment and hosting for static web applications and edge functions).
Functions and triggers
Since one goal of serverless is for developers to focus less on infrastructure and more on application logic, Lambda functions are a key component. These functions encapsulate a single "unit of work." AWS offers runtimes for different languages such as Node.js, Golang, and Python.
One property of these functions is that they are elastic. This means they can handle varying workloads and automatically adapt to changes in demand. Each function runs in its own isolated environment. These functions are usually charged according to a combination of invocations, execution time, and allocated resources (memory).
For Amazon, a common way to invoke Lambda functions is through HTTP calls, much like a REST API. Functions are associated with an endpoint that receives the HTTP call's arguments and passes them to the corresponding function. This lets you apply application logic, such as retrieving items from a shopping cart or performing other actions.
When I started working with this model, I struggled to understand that many responsibilities I used to delegate to my application framework, such as deserializing JSON, retrieving headers, or implementing authentication, are now delegated to the service provider. This transition to serverless architecture can feel a little strange, since everything Express used to do for me, for example, is replaced by services provided by the provider in the AWS Lambda case.
Previously, the code in my application might have looked like this:
const express = require("express");
const jwt = require("jwt");
const authorizer = require("./authorizer");
const app = express();
app.post("/hello", authorizer, (req, res) => {
const { name } = req.body;
res.status(200).json({ message: `Hello, ${name}!` });
});
app.listen(3000, () => {
console.log("Server is running on port 3000.");
});
In AWS Lambda, the code would look like this:
export function hello(event) {
const { name } = JSON.parse(event.body);
return {
message: message: `Hello, ${name}!`,
};
}
We can see how Lambda delegates more responsibility to the service provider, such as routing and server configuration, since the provider receives events and runs the corresponding functions.
Just as we can invoke a Lambda through an HTTP call, that is only one of many triggers we can use to run our functions. Since serverless is meant to let us spend less time writing infrastructure and delegate it to the provider, we can listen for database changes, queue messages, timers, file uploads, and more.
Events and triggers make serverless applications reactive and event-driven. Functions run only when needed in response to specific events, saving resources and ensuring that application capacity automatically adjusts to demand.
Patterns and principles
A crucial point that would have been useful to know before entering the serverless world is that, unlike monolithic services or traditional application development, serverless inherently requires implementing distributed application or microservice patterns.
As mentioned earlier, Lambda functions represent individual units of work. To develop a complete application flow in a serverless environment, we need to split it into multiple processes and carefully consider how to distribute and communicate the logic between them.
To illustrate some of the patterns and good practices we implement in serverless, let us develop a practical application case. Suppose we have an ordering system and want to check whether a user has enough balance to place an order.
Data patterns
Repositories: The term "repositories" can have different definitions and contexts. In domain-driven design, repositories are a way to persist and access the state of "domain entities." They focus on managing and manipulating domain objects, encapsulating the specific data access logic. Therefore, in this context, repositories are not used to abstract and encapsulate data access in general throughout an application.
If you need an abstraction that helps you test your applications by removing a dependency on a specific database, or if you are looking for a way to decouple and replace the strategy used to store data, you may not need to use repositories directly. Instead, you can consider a DataStore or another abstraction that lets you achieve those goals. It is important to remember that repositories are a term specifically associated with domain-driven design and are intended to manage persistence and access to domain objects.
// domain.ts
export interface IRepository<T extends Entity> {
add(entity: T): void;
update(entity: T): void;
get(id: string): Promise<T | null>;
}
Unit of Work: The Unit of Work pattern is used to group transactions and database changes into a single coherent unit. In my interpretation, it can be seen as an evolution of repositories. Like them, Unit of Work is a way to group transactions between domain entities.
They can be as simple as an interface, but you could instantiate as many as you have domain transactions.
// domain.ts
export interface IUnitOfWork {
transactionId: string;
commit(): Promise<void>;
}
A common mistake we can make when not using Unit of Work is creating separate transactions. This can lead to inconsistent data if one of the transactions fails.
In this case, if the user update (userRepo.update(user)) succeeds but adding the transaction (transactRepo.add(transaction)) fails, the data will be left in an inconsistent state. The user's balance will have been reduced, but the transaction will not have been recorded.
function main() {
const amount = 10;
const transaction = transaction.new(amount);
user.reduceBalance(amount);
// two separate transactions are created
// if one fails, the data will be inconsistent
await userRepo.update(user);
await transactRepo.add(transaction);
}
One possible solution would be to use the transaction object offered by our ORM.
function main() {
const amount = 10;
const transaction = transaction.new(amount);
user.reduceBalance(amount);
// this couples us to our database.
const dbTransact = db.beginTran();
await userRepo.update(user, dbTransact);
await transactRepo.add(transaction, dbTransact);
dbTransact.commit();
}
With Unit of Work, operations are grouped into a single coherent transaction. If any operation fails, the entire transaction is rolled back, maintaining data consistency. This avoids inconsistencies and ensures data integrity if errors occur during processing.
function main() {
const amount = 10;
const transaction = transaction.new(amount);
user.reduceBalance(amount);
// internally, the repositories have access to the UnitOfWork
userRepo.update(user);
transactRepo.add(transaction);
unitOfWork.commit();
}
Resilience patterns (Let it crash)
Resilience is an application's ability to recover from errors. In client-server HTTP APIs, a user can resend a request if it fails. But what happens when a request fails between two services or while trying to reach an external service? In those cases, there is no user to resend it.
To address this problem, we implement resilience patterns that let our application recover from failures and keep working even in catastrophic situations. AWS Lambda offers the option by default to retry a Lambda function operation in the event of an error. In addition, when combined with tools such as SNS, SQS, or EventBridge, a set of tools is available to retry and replay events after failures.
Within our application, we can apply the Retry pattern internally, configuring retries for transient failures. This lets the serverless application retry the operation after an error, improving fault tolerance and system stability.
await retryWithExponentialBackoff(() => {
return eventBridgeClient.putEvents({
Entries: [
{
EventBusName: process.env.INTEGRATION_EVENTS_EVENT_BUS!,
Source: process.env.INTEGRATION_EVENTS_SOURCE!,
DetailType: item.name,
Detail: JSON.stringify(item),
},
],
});
});
Besides Retry, I would recommend exploring other patterns you can implement according to your use case, such as Circuit Breaker, Bulkhead, or Fallback. These are part of the Application Resiliency Patterns and can offer additional strategies for ensuring your application's resilience and robustness.
You can find more information about these patterns and their implementation at the following link: Reliability patterns.
Concurrency patterns
For data read and write operations, concurrency is a critical consideration for correct and consistent behavior in environments where multiple processes or threads can access the same data at the same time. In a serverless environment, we must remember that each process operates independently and our application can scale and be served by many processes simultaneously.
Optimistic vs. Pessimistic Concurrency: These patterns refer to different approaches to handling concurrency in data reads and writes. Optimistic concurrency assumes there will be no concurrent write conflicts and allows operations to proceed without locks. Pessimistic concurrency, on the other hand, uses locking or mutual exclusion mechanisms to ensure that conflicts do not occur during concurrent operations.
The concurrency strategy best suited to your needs depends on your application's design. However, these concurrency patterns should be complemented by the resilience approach mentioned above. In both cases, you will likely need to catch exceptions associated with concurrent operations and retry to handle failures.
We can see how a controlled version is applied to the entity in our repository. Before performing an update, the current version of the entity in the database is checked against the expected version. If there is a discrepancy, the update does not take place. This ensures that concurrent updates cannot overwrite changes made by other transactions.
update: (entity: Domain.Entity): void => {
const { id, ...entityValues } = entity;
entityValues.version++;
console.info(convertObjectToDynamoDBUpdate(entityValues));
const {
UpdateExpression,
ExpressionAttributeValues,
ExpressionAttributeNames,
} = convertObjectToDynamoDBUpdate(entityValues);
unitOfWork.register([
{
Update: {
TableName: tableName,
Key: { id: { S: id } },
UpdateExpression: UpdateExpression,
ConditionExpression: "#version = :currentVersion",
ExpressionAttributeNames: {
"#version": "version",
...ExpressionAttributeNames,
},
ExpressionAttributeValues: {
":currentVersion": { N: `${entityValues.version - 1}` },
...ExpressionAttributeValues,
},
},
},
]);
},
Distributed patterns
In distributed environments, where systems consist of multiple interconnected components, patterns and practices that facilitate coordination, scalability, and data management are essential.
CQRS (Command Query Responsibility Segregation): This pattern separates read operations (queries) and write operations (commands) into different data models and business logic. CQRS is nothing magical; it is simply the separation of writes and reads.
The main reason to divide these cases is that they have different needs. For reads, we can optimize efficiency by skipping the repository pattern and accessing the data we need directly through queries. We can also implement a cache layer to improve performance further.
Writes, on the other hand, require stricter validation and implementation of all business rules. They also involve loading related data from different tables to construct a valid and safe record.
By separating read and write responsibilities, we can optimize query performance and ensure data integrity during writes. This allows a more flexible and scalable design, since we can adjust each model and its business logic to its particular needs.
It is important to note that implementing CQRS can add complexity to an application's architecture. Therefore, it is advisable to carefully assess whether the benefits of separating reads and writes outweigh the additional development and maintenance costs.
SAGAS: The SAGAS pattern is used to coordinate and manage distributed transactions and events in a system. In a serverless context, this pattern can be applied to manage complex workflows involving multiple functions and services, ensuring operations are performed consistently and in coordination.
Event Sourcing: In this pattern, events representing changes made in the system are stored instead of the current state. This lets us reconstruct the current state from the stored events and also makes it easier to audit and trace changes.
In conclusion
The patterns discussed in this section are key concepts that would have been beneficial to know before developing serverless and distributed applications. Learning and applying them can make a significant difference in the quality and performance of our applications.
It is important not to apply every pattern indiscriminately to every service and piece of infrastructure. Each technological and architectural decision must be evaluated according to the use case and specific needs. There is no one solution for every scenario. Understanding these patterns and keeping them in mind, however, gives us additional tools to address common challenges and improve our applications.
It is also essential to remember that applications evolve. As they evolve and grow, applying some of the patterns learned here may become necessary. Understanding these concepts gives us the foundation and ability to adapt our applications as needs change.