Build a Realtime Serverless GraphQL API with Websockets on AWS

15 July, 2018

With the release of AWS AppSync we finally have the ability to create realtime serverless apps on AWS. Previously you were forced to spin up EC2 instances in order to create websocket connections as they are not supported by AWS Lambda.

In the tutorial you’ll learn how to build a simple GraphQL API using AWS AppSync. Then you’ll write a client app in vanilla javascript (no frameworks) that receives realtime updates via websockets. Let’s get started!

A standard GraphQL schema apart from the realtime subscription which uses a special syntax to indicate to AWS AppSync which mutation to subscribe to (@aws_subscribe(mutations: ["message"])), in this case the message mutation.

3. Create Mapping Templates

Now we have our schema defined we need to add resolvers for it. If you’re expecting to need to write a lambda function you’d be wrong! AppSync introduces the concept of mapping templates which translate the client request to one the backing store (DynamoDB, elasticsearch etc) understands and then translates the response back to the client again.

To keep things simple we are creating an API without a database. AppSync offers a special type of resolver called a local resolver which does not persist the request data but instead just relays it on to whatever subscribers exist at the time.

Let’s create a directory to house our mapping templates.

$ mkdir mapping-templates

Then let’s create the request template for our message mutation in a file called mapping-templates/Message.request.vtl which will extract the fields from the mutation request.

As you can see we set the data source type to NONE in order to use the local resolver as we do not want to persist the chat messages in a database but instead just forward them to other clients listening for updates.

Our serverless.yml config contains a few environment variables that we must supply. Let’s create a .env file that contains our AWS Account ID and dynamically populates the other variables.

As the webserver will be serving assets from the dist directory we need to add an index.html file that includes the bundle.js file which webpack will generate. Create a file at dist/index.html with the following contents.

12. Conclusion

We’ve set up a serverless GraphQL API with node.js and browser clients consuming realtime updates via websockets. Not bad for <30 minutes work!

Although AppSync is promoted as a managed GraphQL API service, for me its best feature is the ability to serve realtime updates. Previously you would have had to run a server 24/7 to do this. Now you get all the cost savings of serverless and without any of the headaches of managing servers.