Skip to content

Commit ca7fa81

Browse files
authored
feat(compose-eventbridge-custom-bus): bring the example to the standard with a live test (#846)
1 parent 1ae4218 commit ca7fa81

5 files changed

Lines changed: 430 additions & 266 deletions

File tree

‎compose-eventbridge-custom-bus/README.md‎

Lines changed: 143 additions & 113 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
<!--
2-
title: Serverless Framework Compose - EventBridge Custom Event Bus Subscribers
3-
description: Own an EventBridge Custom Event Bus in a stateful service and subscribe functions from other services to it, with ordered and batched delivery, wired together with Serverless Compose.
2+
title: 'Serverless Compose EventBridge Custom Event Bus Subscribers'
3+
description: 'Own an EventBridge Custom Event Bus in a stateful service and subscribe functions from other services to it, with ordered and batched delivery, wired together with Serverless Compose'
44
layout: Doc
55
framework: v4
66
platform: AWS
@@ -10,27 +10,11 @@ authorName: 'Serverless, Inc.'
1010
authorAvatar: 'https://avatars1.githubusercontent.com/u/13742415?s=200&v=4'
1111
-->
1212

13-
# Serverless Framework Compose: EventBridge Custom Event Bus Subscribers
13+
# Subscribe functions to an EventBridge Custom Event Bus with Serverless Compose
1414

15-
The EventBridge [Custom Event Bus](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-custom-bus.html)
16-
routes events to subscribers and keeps every event for a retention period of 1
17-
to 365 days. Consumers attach their own subscribers to a bus that another stack
18-
owns, and each subscriber filters the events and delivers the matching ones to
19-
one target. When the `eventBus` of an `eventBridge` function event is a Custom
20-
Event Bus, the Serverless Framework creates an `AWS::EventsV2::Subscriber` for
21-
the function instead of a rule.
15+
[![Verified](https://raw.githubusercontent.com/serverless/examples/verified/badges/compose-eventbridge-custom-bus.svg)](https://github.com/serverless/examples/blob/verified/results.json)
2216

23-
This example composes three services:
24-
25-
- **`events`**: a stateful, resource-only service that owns the bus and outputs
26-
its ARN. Deploy it once per environment.
27-
- **`orders`**: two consumers of the bus.
28-
- `fulfil` receives one `OrderPlaced` event per invocation, in publish order
29-
within each event group (`ordering: fifo`, `batchSize: 1`).
30-
- `audit` keeps the Custom Event Bus defaults: it receives an array of
31-
events, and undeliverable events go to a dead-letter queue.
32-
- **`producer`**: a function that publishes order events with
33-
`@aws-sdk/client-eventbridgev2`.
17+
The EventBridge [Custom Event Bus](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-custom-bus.html) routes events to subscribers and keeps every event for a retention period of 1 to 365 days. Consumers attach their own subscribers to a bus that another stack owns, and each subscriber filters the events and delivers the matching ones to one target. When the `eventBus` of an [`eventBridge` event](https://www.serverless.com/framework/docs/providers/aws/events/event-bridge#custom-event-bus) is a Custom Event Bus, the Serverless Framework creates an `AWS::EventsV2::Subscriber` for the function instead of a rule. This example owns the bus in one service and subscribes two functions from another service to it, wired together with [Serverless Compose](https://www.serverless.com/framework/docs/guides/compose): one function receives orders one at a time in publish order, the other in batches.
3418

3519
```text
3620
┌──────────────┐ PutEvents ┌──────────────────────┐ subscribers ┌──────────────────────┐
@@ -42,24 +26,118 @@ This example composes three services:
4226
└──────────── ${service:events.OrdersBusArn} (Compose params) ─────────┘
4327
```
4428

45-
## When to use a Custom Event Bus
29+
## What it deploys
4630

47-
AWS recommends the Custom Event Bus for new applications. It fits when several
48-
teams or services consume the same events, when a consumer needs events in
49-
order, or when events must be kept on the bus for later delivery. AWS service
50-
events and SaaS partner events arrive on the default bus or a partner bus, and
51-
reach a Custom Event Bus only through an event source; schedules stay on Classic
52-
rules or EventBridge Scheduler. The
53-
[Choosing a bus](https://www.serverless.com/framework/docs/providers/aws/events/event-bridge#choosing-a-bus)
54-
section of the EventBridge event docs compares the two, including pricing,
55-
Regions and quotas.
31+
Three services, which Compose deploys in this order:
5632

57-
The Custom Event Bus is available in a subset of AWS Regions, and a subscriber
58-
is created in its bus's Region. This example deploys to `us-east-1`, the
59-
Framework's default Region; pass `--region` to deploy all three services to
60-
another Region that offers the Custom Event Bus.
33+
- **`events`**: a stateful, resource-only service with the Custom Event Bus `orders-<stage>`, which keeps events for 7 days, and a stack output with its ARN. Deploy it once per environment.
34+
- **`orders`**: two consumers of the bus.
35+
- `fulfil` receives one `OrderPlaced` event per invocation, in publish order within each event group (`ordering: fifo`, `batchSize: 1`).
36+
- `audit` keeps the Custom Event Bus defaults: it receives an array of events, and events it can't take go to an SQS dead-letter queue, `AuditDlq`.
37+
- A subscriber on the bus for each function, and one IAM delivery role that EventBridge assumes to invoke them.
38+
- **`producer`**: a function, `publish`, that publishes order events with `@aws-sdk/client-eventbridgev2`.
39+
40+
Each function gets an IAM execution role and a CloudWatch Logs log group.
41+
42+
## Prerequisites
43+
44+
- The Serverless Framework CLI: `npm i -g serverless`, which needs [Node.js](https://nodejs.org/). See [Getting started](https://www.serverless.com/framework/docs/getting-started).
45+
- An AWS account, with credentials configured on your machine. See [AWS credentials](https://www.serverless.com/framework/docs/providers/aws/guide/credentials).
46+
- A Serverless account, or a license key in `SERVERLESS_LICENSE_KEY`. The CLI asks you to sign in the first time you run it.
47+
- An AWS Region that offers the Custom Event Bus. It launched in a subset of Regions; [AWS Capabilities by Region](https://builder.aws.com/build/capabilities) lists where it is available. The default quota is 5 Custom Event Buses per account and Region, so the account needs one free.
48+
- The deploying identity needs `iam:PassRole` on the delivery role; see [The delivery role](#the-delivery-role).
49+
50+
## Deploy
51+
52+
Install the producer's dependencies, then deploy all three services from this directory:
53+
54+
```bash
55+
cd producer && npm ci && cd ..
56+
serverless deploy
57+
```
58+
59+
Without options, the deploy uses the stage `dev` and the Region `us-east-1`. To change them, pass `--stage` or `--region`, and pass the same options to every later command, including `serverless remove`. Compose deploys `events` first, then `orders` and `producer`.
60+
61+
You should see output like this:
6162

62-
## How the services are wired
63+
```text
64+
Serverless ϟ Compose
65+
66+
✔ events
67+
OrdersBusArn: arn:aws:events:us-east-1:123456789012:event-busv2/orders-dev/buy4dk6nb4f40wofzbygbi3fm
68+
ServerlessDeploymentBucketName: serverless-framework-deployments-us-east-1-xxxxxxxx-xxxx
69+
70+
✔ producer
71+
PublishLambdaFunctionQualifiedArn: arn:aws:lambda:us-east-1:123456789012:function:compose-eventbus-producer-dev-publish:1
72+
ServerlessDeploymentBucketName: serverless-framework-deployments-us-east-1-xxxxxxxx-xxxx
73+
74+
✔ orders
75+
AuditLambdaFunctionQualifiedArn: arn:aws:lambda:us-east-1:123456789012:function:compose-eventbus-orders-dev-audit:1
76+
FulfilLambdaFunctionQualifiedArn: arn:aws:lambda:us-east-1:123456789012:function:compose-eventbus-orders-dev-fulfil:1
77+
ServerlessDeploymentBucketName: serverless-framework-deployments-us-east-1-xxxxxxxx-xxxx
78+
79+
Results: 3 services succeeded, 0 failed, 0 skipped, 3 total Time: 1m 59s
80+
```
81+
82+
## Try it
83+
84+
Invoke the producer. It publishes `count` `OrderPlaced` events (1 to 10, default 3) for one customer, one after another, and returns their sequence numbers:
85+
86+
```bash
87+
serverless producer invoke --function publish --data '{"count":5}'
88+
```
89+
90+
```json
91+
{
92+
"customerId": "customer-c86f74c2",
93+
"published": [
94+
{
95+
"sequence": 1,
96+
"orderId": "df3fb693-4d15-4bd3-b55b-a7de18c2e3b0",
97+
"eventId": "6a8f5c0a-93da-4cc3-890d-059d289f693b"
98+
},
99+
...
100+
{
101+
"sequence": 5,
102+
"orderId": "aa25fe11-dff6-4cce-a3fe-ac1559ea4a12",
103+
"eventId": "4e03564d-d9b4-4b56-be83-142dc119899e"
104+
}
105+
]
106+
}
107+
```
108+
109+
Read `fulfil`'s log. It logs one event per invocation, with `sequence` in publish order:
110+
111+
```bash
112+
serverless orders logs --function fulfil
113+
```
114+
115+
Among Lambda's own `START`, `END` and `REPORT` lines, the handler's lines are:
116+
117+
```text
118+
INFO {"handler":"fulfil","orderId":"df3fb693-4d15-4bd3-b55b-a7de18c2e3b0","sequence":1,"id":"462b26d6-186a-41d1-b709-eeeac8ced30e"}
119+
INFO {"handler":"fulfil","orderId":"ff8529b0-cb2a-4ffa-8322-d5c6366d3024","sequence":2,"id":"cfe935e4-ebb9-40aa-8c10-fe602a353274"}
120+
INFO {"handler":"fulfil","orderId":"3286fe6f-0de1-4082-90ec-bd6f30d1a480","sequence":3,"id":"d2e63ed3-62d8-48e0-95f6-45a099595c63"}
121+
INFO {"handler":"fulfil","orderId":"fed2742b-5e5d-4f0d-a205-0bb998d298b6","sequence":4,"id":"d231158a-6609-49d5-a145-71165a3a2140"}
122+
INFO {"handler":"fulfil","orderId":"aa25fe11-dff6-4cce-a3fe-ac1559ea4a12","sequence":5,"id":"1937d9e1-22b0-4475-804c-ea9a65fd30d3"}
123+
```
124+
125+
Read `audit`'s log. It logs the size of each array it receives; how the five events are split into batches, and in what order, varies from run to run:
126+
127+
```bash
128+
serverless orders logs --function audit
129+
```
130+
131+
```text
132+
INFO {"handler":"audit","received":4,"orders":["ff8529b0-cb2a-4ffa-8322-d5c6366d3024","fed2742b-5e5d-4f0d-a205-0bb998d298b6","aa25fe11-dff6-4cce-a3fe-ac1559ea4a12","3286fe6f-0de1-4082-90ec-bd6f30d1a480"]}
133+
INFO {"handler":"audit","received":1,"orders":["df3fb693-4d15-4bd3-b55b-a7de18c2e3b0"]}
134+
```
135+
136+
If a command prints `No existing streams for the function`, or not all lines are there yet, wait a few seconds and run it again.
137+
138+
## How it works
139+
140+
### How the services are wired
63141

64142
The bus lives in its own service, so the consumers and the producer can be
65143
deployed, changed and removed without touching it:
@@ -102,7 +180,7 @@ The Framework recognizes a Custom Event Bus from its ARN, which contains
102180
`:event-busv2/`. A Framework variable such as `${param:ordersBusArn}` resolves
103181
before packaging, so each `eventBridge` event below creates a subscriber.
104182

105-
## The consumers
183+
### The consumers
106184

107185
```yaml
108186
# orders/serverless.yml
@@ -134,7 +212,7 @@ functions:
134212
`pattern` becomes the subscriber's filter, in the same syntax as a rule's event
135213
pattern.
136214

137-
### `fulfil`: one event at a time, in order
215+
#### `fulfil`: one event at a time, in order
138216

139217
With `ordering: fifo`, EventBridge delivers the events of each event group in
140218
the order they were published. The producer sets the event group with
@@ -154,7 +232,7 @@ For a FIFO subscriber, use an SQS FIFO queue as its dead-letter queue. `fulfil`
154232
has none, so an event that is still undeliverable after the retry policy is
155233
dropped.
156234

157-
### `audit`: the Custom Event Bus defaults
235+
#### `audit`: the Custom Event Bus defaults
158236

159237
`audit` sets no delivery options, so it gets the Custom Event Bus defaults:
160238

@@ -181,7 +259,7 @@ for moving a consumer from a Classic bus, and
181259
[Settings on a Custom Event Bus](https://www.serverless.com/framework/docs/providers/aws/events/event-bridge#settings-on-a-custom-event-bus)
182260
for every key, including `maximumBatchingWindow`.
183261

184-
## The delivery role
262+
### The delivery role
185263

186264
A subscriber invokes its function through an IAM role, not a Lambda
187265
permission. For `orders`, the Framework creates one delivery role,
@@ -209,7 +287,7 @@ EventBridge:
209287
To use a role you manage instead, set `role` on the `eventBridge` event. See
210288
[The delivery role](https://www.serverless.com/framework/docs/providers/aws/events/event-bridge#the-delivery-role).
211289

212-
## The producer
290+
### The producer
213291

214292
The producer publishes with `PutEventsCommand` from
215293
`@aws-sdk/client-eventbridgev2`, and its execution role allows
@@ -245,64 +323,22 @@ build:
245323
- '!@aws-sdk/client-eventbridgev2'
246324
```
247325

248-
## Usage
249-
250-
Install the producer's dependencies:
251-
252-
```bash
253-
cd producer && npm install && cd ..
254-
```
255-
256-
### Deploy
257-
258-
Deploy all three services. Compose deploys `events` first, then `orders` and
259-
`producer`:
260-
261-
```bash
262-
serverless deploy
263-
```
264-
265-
### Publish events
266-
267-
Invoke the producer. It publishes `count` `OrderPlaced` events (1 to 10,
268-
default 3) for one customer, one after another, and returns their sequence
269-
numbers:
270-
271-
```bash
272-
serverless producer invoke --function publish --data '{"count":5}'
273-
```
274-
275-
### Check the consumers
276-
277-
`fulfil` logs one event per invocation, with `sequence` in publish order. The
278-
excerpts below show only the handlers' JSON lines; `serverless logs` also
279-
prints each line's timestamp and request id, and the START, END and REPORT
280-
lines.
281-
282-
```bash
283-
serverless orders logs --function fulfil
284-
```
285-
286-
```text
287-
{"handler":"fulfil","orderId":"46bcf29d-…","sequence":1,…}
288-
{"handler":"fulfil","orderId":"3fc7291c-…","sequence":2,…}
289-
{"handler":"fulfil","orderId":"c0ec4506-…","sequence":3,…}
290-
{"handler":"fulfil","orderId":"2a18361d-…","sequence":4,…}
291-
{"handler":"fulfil","orderId":"ae0265ec-…","sequence":5,…}
292-
```
293-
294-
`audit` logs the size of each array it receives. How the five events are split
295-
into batches, and in what order, varies from run to run:
326+
## When to use a Custom Event Bus
296327

297-
```bash
298-
serverless orders logs --function audit
299-
```
328+
AWS recommends the Custom Event Bus for new applications. It fits when several
329+
teams or services consume the same events, when a consumer needs events in
330+
order, or when events must be kept on the bus for later delivery. AWS service
331+
events and SaaS partner events arrive on the default bus or a partner bus, and
332+
reach a Custom Event Bus only through an event source; schedules stay on Classic
333+
rules or EventBridge Scheduler. The
334+
[Choosing a bus](https://www.serverless.com/framework/docs/providers/aws/events/event-bridge#choosing-a-bus)
335+
section of the EventBridge event docs compares the two, including pricing,
336+
Regions and quotas.
300337

301-
```text
302-
{"handler":"audit","received":1,"orders":["3fc7291c-…"]}
303-
{"handler":"audit","received":3,"orders":["2a18361d-…","ae0265ec-…","c0ec4506-…"]}
304-
{"handler":"audit","received":1,"orders":["46bcf29d-…"]}
305-
```
338+
The Custom Event Bus is available in a subset of AWS Regions, and a subscriber
339+
is created in its bus's Region. This example deploys to `us-east-1`, the
340+
Framework's default Region; pass `--region` to deploy all three services to
341+
another Region that offers the Custom Event Bus.
306342

307343
## Personal and preview stages
308344

@@ -315,12 +351,11 @@ resolver pinned to `dev`. The
315351
shows that pattern, and the Compose guide describes it in
316352
[Referencing a service deployed to a different stage](https://www.serverless.com/framework/docs/guides/compose#referencing-a-service-deployed-to-a-different-stage).
317353

318-
## Removal
354+
## Cost and cleanup
355+
356+
While the example is deployed, Amazon EventBridge bills the size of the events published to the bus and delivered to each subscriber and the storage of the events the bus retains, Lambda bills each invocation and the functions' compute time, Amazon SQS bills requests to the dead-letter queue, and CloudWatch Logs bills the functions' stored log data. See [Amazon EventBridge pricing](https://aws.amazon.com/eventbridge/pricing/), [Lambda pricing](https://aws.amazon.com/lambda/pricing/), [Amazon SQS pricing](https://aws.amazon.com/sqs/pricing/) and [CloudWatch pricing](https://aws.amazon.com/cloudwatch/pricing/).
319357

320-
A bus with subscribers attached can't be deleted, so remove the consumers and
321-
the producer before `events`. `serverless remove` runs in the reverse of the
322-
deploy order, so from this directory it removes `orders` and `producer` first,
323-
then `events`:
358+
A bus with subscribers attached can't be deleted, so remove the consumers and the producer before `events`. `serverless remove` runs in the reverse of the deploy order, so from this directory it removes `orders` and `producer` first, then `events`:
324359

325360
```bash
326361
serverless remove
@@ -333,16 +368,11 @@ serverless remove --service=orders,producer
333368
serverless remove --service=events
334369
```
335370

336-
The bus has no `DeletionPolicy`, so removing `events` deletes the bus and the
337-
events it retains. For a long-lived environment, add `DeletionPolicy: Retain`
338-
and `UpdateReplacePolicy: Retain` to `OrdersBus` in `events/serverless.yml`; the
339-
bus then stays in the account after `serverless remove`, and you delete it
340-
yourself.
371+
The bus has no `DeletionPolicy`, so removing `events` deletes the bus and the events it retains. For a long-lived environment, add `DeletionPolicy: Retain` and `UpdateReplacePolicy: Retain` to `OrdersBus` in [`events/serverless.yml`](https://github.com/serverless/examples/blob/v4/compose-eventbridge-custom-bus/events/serverless.yml); the bus then stays in the account after `serverless remove`, and you delete it yourself.
341372

342-
## Learn more
373+
## Next steps
343374

344-
- [EventBridge event: Custom Event Bus](https://www.serverless.com/framework/docs/providers/aws/events/event-bridge#custom-event-bus)
345-
- [Serverless Compose](https://www.serverless.com/framework/docs/guides/compose)
346-
- [Function build configuration](https://www.serverless.com/framework/docs/providers/aws/guide/building)
347-
- [Amazon EventBridge Custom Event Bus](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-custom-bus.html)
348-
- [Ordering on a Custom Event Bus](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-custom-bus-ordering.html)
375+
- Read [EventBridge events: Custom Event Bus](https://www.serverless.com/framework/docs/providers/aws/events/event-bridge#custom-event-bus) for every subscriber setting, subscribing to a bus in another account, and moving a consumer from a Classic bus.
376+
- Read [Serverless Compose](https://www.serverless.com/framework/docs/guides/compose) for parameters between services and deploying one service at a time.
377+
- Match AWS service events or your own on the default bus with a rule, as the [EventBridge rule example](https://github.com/serverless/examples/tree/v4/aws-node-eventbridge-rule) does.
378+
- Read [Ordering on a Custom Event Bus](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-custom-bus-ordering.html) in the EventBridge user guide.
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
{
2+
"title": "Serverless Compose EventBridge Custom Event Bus Subscribers",
3+
"description": "Own an EventBridge Custom Event Bus in a stateful service and subscribe functions from other services to it, with ordered and batched delivery, wired together with Serverless Compose",
4+
"language": "node",
5+
"platform": "AWS",
6+
"framework": "v4",
7+
"author": {
8+
"name": "Serverless, Inc.",
9+
"link": "https://github.com/serverless",
10+
"avatar": "https://avatars1.githubusercontent.com/u/13742415?s=200&v=4"
11+
},
12+
"services": [
13+
"lambda",
14+
"eventbridge",
15+
"sqs",
16+
"iam",
17+
"logs"
18+
],
19+
"test": {
20+
"tier": "fast",
21+
"checks": [
22+
{
23+
"script": {
24+
"path": "test/smoke.mjs"
25+
}
26+
}
27+
]
28+
}
29+
}

0 commit comments

Comments
 (0)