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.
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.
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:
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