In this example we will look at how to use SQS to create a queue in our serverless app using SST. We’ll be creating a simple queue system.

Requirements

Create an SST app

Let’s start by creating an SST app.

$ npx create-sst@latest --template=minimal/typescript-starter queue
$ cd queue
$ npm install

By default, our app will be deployed to an environment (or stage) called dev and the us-east-1 AWS region. This can be changed in the sst.json in your project root.

{
  "name": "queue",
  "region": "us-east-1",
  "main": "stacks/index.ts"
}

Project layout

An SST app is made up of two parts.

  1. stacks/ — App Infrastructure

    The code that describes the infrastructure of your serverless app is placed in the stacks/ directory of your project. SST uses AWS CDK, to create the infrastructure.

  2. services/ — App Code

    The code that’s run when your API is invoked is placed in the services/ directory of your project.

Adding SQS Queue

Amazon SQS is a reliable and high-throughput message queuing service. You are charged based on the number of API requests made to SQS. And you won’t get charged if you are not using it.

Replace the stacks/MyStack.ts with the following.

import { StackContext, Queue, Api } from "@serverless-stack/resources";

export function MyStack({ stack }: StackContext) {
  // Create Queue
  const queue = new Queue(stack, "Queue", {
    consumer: "functions/consumer.handler",
  });
}

This creates an SQS queue using Queue. And it has a consumer that polls for messages from the queue. The consumer function will run when it has polled 1 or more messages.

Setting up the API

Now let’s add the API.

Add this below the Queue definition in stacks/MyStack.ts.

// Create the HTTP API
const api = new Api(stack, "Api", {
  defaults: {
    function: {
      // Bind the table name to our API
      bind: [queue],
    },
  },
  routes: {
    "POST /": "functions/lambda.handler",
  },
});

// Show the API endpoint in the output
stack.addOutputs({
  ApiEndpoint: api.url,
});

Our API simply has one endpoint (the root). When we make a POST request to this endpoint the Lambda function called handler in services/functions/lambda.ts will get invoked.

We’ll also bind our queue to our API.

Adding function code

We will create two functions, one for handling the API request, and one for the consumer.

Replace the services/functions/lambda.ts with the following.

export async function handler() {
  console.log("Message queued!");
  return {
    statusCode: 200,
    body: JSON.stringify({ status: "successful" }),
  };
}

Add a services/functions/consumer.ts.

export async function handler() {
  console.log("Message processed!");
  return {};
}

Now let’s test our new API.

Starting your dev environment

SST features a Live Lambda Development environment that allows you to work on your serverless apps live.

$ npm start

The first time you run this command it’ll take a couple of minutes to deploy your app and a debug stack to power the Live Lambda Development environment.

===============
 Deploying app
===============

Preparing your SST app
Transpiling source
Linting source
Deploying stacks
dev-queue-my-stack: deploying...

 ✅  dev-queue-my-stack


Stack dev-queue-my-stack
  Status: deployed
  Outputs:
    ApiEndpoint: https://i8ia1epqnh.execute-api.us-east-1.amazonaws.com

The ApiEndpoint is the API we just created.

Let’s test our endpoint with the SST Console. The SST Console is a web based dashboard to manage your SST apps. Learn more about it in our docs.

Go to the API tab and click the Send button of the POST / function to send a POST request.

API explorer response

After you see a success status in the logs, go to the Local tab in the console to see all function invocations. Local tab displays real-time logs from your Live Lambda Dev environment.

Local tab response without queue

You should see Message queued! logged in the console.

Sending message to our queue

Now let’s send a message to our queue.

Replace the services/functions/lambda.ts with the following.

import AWS from "aws-sdk";
import { Queue } from "@serverless-stack/node/queue";

const sqs = new AWS.SQS();

export async function handler() {
  // Send a message to queue
  await sqs
    .sendMessage({
      // Get the queue url from the environment variable
      QueueUrl: Queue.Queue.queueUrl,
      MessageBody: JSON.stringify({ ordered: true }),
    })
    .promise();

  console.log("Message queued!");

  return {
    statusCode: 200,
    body: JSON.stringify({ status: "successful" }),
  };
}

Here we are getting the queue url from the environment variable, and then sending a message to it.

Let’s install the aws-sdk package in the services/ folder.

$ npm install aws-sdk

And now if you head over to your console and hit the Send button again in API explorer, you’ll notice in the Local tab that our consumer is called. You should see Message processed! being printed out.

Local tab response with queue

Deploying to prod

To wrap things up we’ll deploy our app to prod.

$ npx sst deploy --stage prod

This allows us to separate our environments, so when we are working in dev, it doesn’t break the API for our users.

Cleaning up

Finally, you can remove the resources created in this example using the following commands.

$ npx sst remove
$ npx sst remove --stage prod

Conclusion

And that’s it! We’ve got a completely serverless queue system. Check out the repo below for the code we used in this example. And leave a comment if you have any questions!