Lambda functions and WebSockets can be seen as concepts difficult to reconcile. Lambdas are ephemeral by nature. They appear when invoked and then disappear sometime after they have finished working. WebSockets, on the contrary, maintain stable, long-living connections between one server and many clients.

The AWS APIGateway offers the possibility to bring these two things together, combining the advantages of the Lambda on-demand model with the power of WebSockets’ real-time bidirectional communication.

In this article, we describe how to implement a WebSocket server using AWS API Gateway and Lambda functions. We will use the Serveless framework to set up the infrastructure and deploy the solution and Go as the programming language.

Serverless has been chosen because it is an easy and well-documented way to define infrastructure as code. Go has been chosen because it guarantees it has the potential to optimise Lambda costs and provide low cold-start latency, an important feature for the implementation of such a model.


A Simple WebSocket Server and What Clients Can Do

To make things concrete, we are going to implement a simple WebSocket server. The goal of this server is to broadcast, as an echo, each message received from one client to all connected clients.

Image for post

An echo-broadcasting server

As we can see from the diagram, each client connects to the server, sends messages to be broadcast by the server to all connected clients, and, in the end, disconnects from the server.

In other words, a client can trigger three types of events:

  • connect to the server
  • disconnect from the server
  • send a message to the server

The server, on the other side, has to react appropriately to these events. The way it reacts is codified using Lambda function(s).

#go #serverless #api #aws #programming #lambda

WebSockets on Demand With AWS Lambda, Serverless Framework, and Go
4.15 GEEK