Migrating to Serverless: Building the Bridge
Setting up AWS EventBridge as the first step in the migration to a serverless architecture.
When we built the first version of Street Art Cities, we didn’t think it would become a global community with tens of thousands of monthly active users. Therefore, we built the platform as a quick MVP in PHP, which then quickly grew with dozens of new features, an API for our mobile app and another API for our partners that license our content.
A few months ago, we decided to start migrating over the platform to a fully serverless infrastructure powered by Node and AWS Lambda.
Due to limited engineering resources, we knew that the migration would take place slowly, replacing each part of our platform as we wanted to revamp or extend features that related to those parts. We wanted to keep the flexibility to leave the PHP side of the platform running as-is, but slowly start moving some of the logic to Node.
The first step we took was utilising AWS EventBridge, a scalable serverless event bus. This allowed us to use events that took place on the legacy platform as triggers to run Lambdas and other workflows (I love Step Functions!) on the new platform.
Publishing events from legacy code
EventBridge by default creates a bus called ‘default’. The AWS SDK makes it very easy to publish events to this bus. Below is some sample PHP code, but the structure is very similar in all languages the AWS SDK supports:
For each event, you will need to define:
- EventBusName: The bus you’re pushing to. You define this when you create an event bus, or can use the
- Source: A string to define the event source. This can be whatever you want it to be, as long as it doesn’t start with
aws., since that namespace is reserved for events coming from other AWS services.
- DetailType: The event type, which you can use as a filter in your event rules.
- Detail: Any JSON string (can be an object or an array or anything else that is valid JSON) with the event data.
Listening to events
The Serverless framework has first-party support for EventBridge, so defining a Lambda function to listen to a particular subset of the events that come through your event bus is very simple:
That will result in your lambda being invoked with an event that looks like this:
If you turn on schema discovery for your default bus, AWS will automatically attempt to create JSON schemas based on the events it sees in the bus. This can serve as an always up-to-date automatic documentation resource for your events. It even allows you to download bindings in Typescript, Python and Java for use in your code!