We’re excited to announce the release of Serverless Cloud Events, a new feature that lets developers easily build event-driven serverless applications. Serverless Cloud already had support for Data and Storage events, allowing developers to write code that reacts to item and object changes. Now, with Serverless Cloud Events, developers can publish and schedule custom events and process them asynchronously with automatic throttling and retries.
Events let you do work "in the background" and allow you to decouple your application to make it more scalable and resilient to errors. Events can also be scheduled for up to 1 year "in the future" if you need to do the work at a later time.
For example, instead of sending a welcome email to a new user immediately in an `api.post()` handler, you can send a "user.joined" event and send the email from the event handler instead. This makes your API much more responsive and means your API will not fail if your downstream email provider is unavailable.
Another advantage of event-driven applications is that they are much easier to extend. For example, if you decide that you want to add billing to your application, you can write an additional handler that listens for that event and completes that process.
Serverless Cloud Events opens up several new use cases, including:
- Background tasks from API requests
- Reminder/follow-up emails
- Delayed notification features
- Analytics processing and usage tracking
- Marketing/sales workflow automation
- Interactive bots
- Throttling traffic spikes for downstream services
- Reliably making requests to third-party services
- Decoupling your application
- Processing high volumes of incoming data (e.g. IoT)
- And many more
Publishing events with "events.publish()"
To publish an event you use the "events.publish()" method, and provide a name and a "body" that contains the data you want to send.
For example, this will publish a "user.joined" event:
You can delay when an event is published using the "after" option. For example, this will send the "user.joined" event in one day:
Handling events with "events.on()"
To handle an event, you use the "events.on()" method, and provide the event name and a handler function.
For example, this will call the handler when a "user.joined" event is received.
There can be more than one handler for a given event name. To add another handler, just call "events.on()" again with the same event name. Your handlers will be called in the order they are defined in your code. If any of your handlers throw an error, they will be retried for up to 14 days, after which the event will be dropped.
Let us know what you think!
Make sure to sign up for Serverless Cloud if you haven't already, and give Events a try. Check out the docs and join our Slack community. We'd love your feedback on Serverless Cloud and the new events feature..