A bit of structure for Serverless

Dave Townsend
unbounded.io
Published in
2 min readMar 27, 2017

--

As of late, I’ve been spending quite a bit of time working with the Serverless Framework and have certainly become a fan. One of the many nice features of the framework is a robust CLI story that allows you to get an application up and running quickly.

Typing this…

sls create -t aws-nodejs

…creates this.

├── handler.js
└── serverless.yml

A good (humble) starting point, but you will likely need to build out a directory structure that can support a larger application, scale organically and keep things logically organized.

After having spent the last 6-weeks or so building out a mobile back-end with the Serverless Framework, I thought I’d share how I’ve structured things.

A Place to Start

Here is the breakdown of an example structure.

├── buildspec.yml
├── docs
├── node_modules
├── package.json
├── src
│ ├── lib
│ └── services
│ ├── booking
│ │ ├── env.yml
│ │ └── serverless.yml
│ ├── notification
│ │ ├── env.yml
│ │ └── serverless.yml
│ ├── tracking
│ │ ├── env.yml
│ │ └── serverless.yml
│ └── vessel
│ ├── env.yml
│ └── serverless.yml
└── test
├── lib
└── services
├── booking
├── notification
├── tracking
└── vessel

Note: None of the JS files are shown, since they are not relevant for the example

From the Top Down

We’re using AWS CodePipeline/CodeBuild for CI/CD, hence the buildspec.yml file.

docs
The docs directory is where we are storing the AWS API Gateway exported swagger/postman API’s. This turned out to be convenient for our mobile team, since they only need to clone the repo and import the docs into postman to begin interacting with the API’s.

node_modules and package.json are right at home in the root.

src
As with a typical JS app, there is a src directory which is built out from there.

src/lib — contains internally created libraries that can be further nested as needed for functional segregation.

src/services — is comprised of nested directories for each Serverless service. In my example, booking, notification, tracking and vessel are independently deployable Serverless services that represent a BoundedContext. Consequently, each service directory has its own serverless.yml, (optional) env.yml file and should contain anything else required for that service — e.g., config for infra, security, etc.

test
The test directory simply follows the same pattern as the src directory for housing the various unit/integration tests for each function. This keeps things easy to find as the number of services grow. The details of testing are a topic for another post.

Evolving

This structure, as we have it internally, is a single Git repo. However, with each service being completely independent, services could be (with minimal effort) broken out into their own repo for an individual service team to manage.

In conclusion…

We have found that this works well for for our setup. Comments and suggestions for improvement welcome.

--

--