Mastering AWS Lambda: Build a Serverless Order Service with Serverless Framework
This article walks you through the fundamentals of serverless architecture, demonstrates how to create and configure AWS Lambda functions for an order‑processing workflow, integrates them with API Gateway, SQS, and the Serverless Framework, and shows how to test, deploy, and clean up the entire solution.
Introduction
Microservice architecture differs from traditional monolithic applications by splitting a single app into multiple independent services, each of which can be built and deployed separately. Extending this idea leads to serverless computing, where the underlying servers are managed by the cloud provider and developers focus solely on business logic.
A typical serverless offering is AWS Lambda . Despite sharing the name with Java 8 lambdas, AWS Lambda is a completely different compute service that runs code without requiring you to provision or manage servers.
AWS Lambda Overview
AWS Lambda lets you run code for virtually any type of application or backend service. You simply upload your function code, and Lambda handles execution, scaling, and high‑availability automatically.
Think of a Lambda as a single‑purpose method exposed as a service.
How to Invoke a Lambda
To create a Lambda function, log in to the AWS console, open the Lambda service, and click Create function . Choose a runtime (e.g., Node.js) and configure a trigger.
Common triggers include API Gateway, ALB, CloudFront, DynamoDB, S3, SNS, and SQS, as well as many non‑AWS event sources.
API Gateway (most common for HTTP calls)
ALB – Application Load Balancer
CloudFront
DynamoDB
S3
SNS – Simple Notification Service
SQS – Simple Queue Service
After configuring a trigger, you can test the function directly from the console.
Demo: Distributed Order Service
The demo illustrates a typical order‑processing scenario: when a user places an order and requests an invoice, the order service sends a message to an SQS queue, and a separate invoice service consumes that message to generate an invoice.
Architecture
Order Service (Lambda)
Invoice Service (Lambda)
Both services are defined using the Serverless Framework, which simplifies CloudFormation template authoring.
Serverless Framework
The Serverless Framework abstracts away raw CloudFormation (CFT) syntax, providing a concise YAML configuration for functions, resources, and provider settings.
Installation
npm update -g serverless sls -versionConfiguration
Configure AWS credentials for the framework:
serverless config credentials --provider aws --key YOUR_AK --secret YOUR_SK --profile custom-profileCreating a Serverless Application
sls create --template aws-nodejs --path ./demo --name lambda-sqs-lambdaThis generates a project with handler.js and serverless.yml. Initialize the Node.js project and install dependencies:
npm init -y npm install uuid aws-sdkserverless.yml (core configuration)
service: lambda-sqs-lambda
provider:
name: aws
runtime: nodejs12.x
region: ap-northeast-1
stage: dev
iamRoleStatements:
- Effect: Allow
Action:
- sqs:SendMessage
Resource:
- Fn::GetAtt: [receiverQueue, Arn]
functions:
order:
handler: app/order.checkout
events:
- http:
method: post
path: order
invoice:
handler: app/invoice.generate
timeout: 30
events:
- sqs:
arn:
Fn::GetAtt: [receiverQueue, Arn]
resources:
Resources:
receiverQueue:
Type: AWS::SQS::Queue
Properties:
QueueName: ${self:custom.conf.queueName}
custom:
conf: ${file(conf/config.json)}Order Lambda Function (app/order.js)
'use strict';
const config = require('../conf/config.json');
const AWS = require('aws-sdk');
const sqs = new AWS.SQS();
const { v4: uuidv4 } = require('uuid');
module.exports.checkout = async (event, context, callback) => {
console.log(event);
let statusCode = 200;
let message;
if (!event.body) {
return {
statusCode: 400,
body: JSON.stringify({ message: 'No order body was found' }),
};
}
const region = context.invokedFunctionArn.split(':')[3];
const accountId = context.invokedFunctionArn.split(':')[4];
const queueName = config['queueName'];
const queueUrl = `https://sqs.${region}.amazonaws.com/${accountId}/${queueName}`;
const orderId = uuidv4();
try {
await sqs.sendMessage({
QueueUrl: queueUrl,
MessageBody: event.body,
MessageAttributes: {
orderId: {
StringValue: orderId,
DataType: 'String',
},
},
}).promise();
message = 'Order message is placed in the Queue!';
} catch (error) {
console.log(error);
message = error;
statusCode = 500;
}
return {
statusCode,
body: JSON.stringify({ message, orderId }),
};
};Invoice Lambda Function (app/invoice.js)
module.exports.generate = (event, context, callback) => {
console.log(event);
try {
for (const record of event.Records) {
const messageAttributes = record.messageAttributes;
console.log('OrderId -->', messageAttributes.orderId.stringValue);
console.log('Message Body -->', record.body);
const reqBody = JSON.parse(record.body);
// Simulate a 20‑second invoice generation delay
setTimeout(() => {
console.log('Receipt is generated and sent to:' + reqBody.email);
}, 20000);
}
} catch (error) {
console.log(error);
}
};Running the Demo
Deploy the service with: sls deploy -v The deployment creates the Lambda functions, an API Gateway endpoint, an SQS queue, and an S3 bucket for the deployment package.
Test the order API by sending a POST request to the endpoint. The request triggers the order Lambda, which puts a message onto the SQS queue. The invoice Lambda, triggered by the queue, consumes the message, waits 20 seconds, and logs that the receipt has been sent.
Cleaning Up
To avoid incurring charges, remove all resources with:
sls removeConclusion
AWS Lambda exemplifies serverless computing, allowing you to build fine‑grained services without managing servers. Combined with other AWS services (API Gateway, SQS, S3, etc.) and the Serverless Framework, you can quickly create, test, and deploy end‑to‑end workflows while keeping the infrastructure code concise and portable.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
