# eb-event-routing

Part of **EB**

<!-- intent-backlink:auto -->

> 💡 **Path Selection**: This skill is one implementation path for [Route events to target services](../../intent/eb-route-targets/SKILL.md). If you're unsure which path to take, check the routing skill first.

# EventBridge Event Routing

## Capabilities Overview

| Sub-capability | Calling Mode | Description |
|--------|----------|------|
| Create Event Rule | Synchronous | Creates an event rule in EventBridge to filter and route events based on specified patterns and targets. |
| Delete Event Rule | Synchronous | Deletes an existing event routing rule. |
| Update Event Rule Configuration | Synchronous | Updates the configuration of an existing event rule. |
| Test Event Pattern Match | Synchronous | Tests whether an event matches a given pattern. |
| Delete Event Targets | Synchronous | Removes targets from an event rule. |
| Update Event Rule | Synchronous | Modifies an existing event rule configuration. |
| List Event Rules | Synchronous | Retrieves all event rules associated with an event bus. |
| Get Rule Details | Synchronous | Fetches detailed information about a specific event rule. |
| Create Event Targets | Synchronous | Defines destinations where matched events should be sent. |
| Disable Event Rule | Synchronous | Temporarily disables an event rule without deleting it. |

## API Calling Patterns

### Authentication
The primary authentication method uses AccessKey ID and AccessKey Secret in the Authorization header.

- Header format: `Authorization: acs <AccessKeyId>:<Signature>`
- Environment variable: `ALIBABA_CLOUD_ACCESS_KEY_ID` and `ALIBABA_CLOUD_ACCESS_KEY_SECRET`
- Alternative methods exist but this signature-based approach is recommended for REST API calls.

### Service Endpoint
The API uses region-specific endpoints with the following pattern:

`https://{account-id}.eventbridge.{region}.aliyuncs.com`

Common regions include:
- cn-hangzhou
- cn-shanghai  
- cn-shanghai

For international accounts, use: `https://{account-id}.eventbridge.intl.aliyuncs.com`

### Synchronous API Pattern
All EventBridge Event Routing operations follow a synchronous request-response pattern:

1. Client sends a POST request with JSON payload to the appropriate endpoint
2. Server processes the request immediately 
3. Server returns a JSON response with success/failure status
4. Client handles the response based on the returned status code and message

Key headers required:
- `Content-Type: application/json;charset=UTF-8`
- `x-eventbridge-version: 2020-04-01`
- `Authorization: acs <AccessKeyId>:<Signature>`
- `Date: <RFC1123 formatted date>`

No polling or async handling is required as all operations complete immediately.

## Parameter Reference

### Create Event Rule

| Parameter | Type | Required | Default | Constraints | Description |
|------|------|------|--------|------|------|
| EventBusName | string | true | | | The name of the event bus. |
| RuleName | string | true | | | The name of the event rule. |
| FilterPattern | string | true | | max length 8192 chars | The event pattern, in JSON format. Supported pattern types are stringEqual and stringExpression. |
| Status | string | false | ENABLE | one of: ENABLE, DISABLE | The status of the event rule. |
| Description | string | false | | | The description of the event rule. |
| EventTargets | array<object> | false | | | A list of event targets. |

### Delete Event Rule

| Parameter | Type | Required | Default | Constraints | Description |
|------|------|------|--------|------|------|
| EventBusName | string | true | | | The name of the event bus. |
| RuleName | string | true | | | The name of the event rule that you want to delete. |

### Update Event Rule Configuration

| Parameter | Type | Required | Default | Constraints | Description |
|------|------|------|--------|------|------|
| EventBusName | string | true | | | The name of the event bus. |
| RuleName | string | true | | | The name of the event rule. |
| FilterPattern | string | true | | max 5 expressions per field in map structure | The event pattern, in JSON format. |
| Status | string | false | ENABLE | one of: ENABLE, DISABLE | The status of the event rule. |
| Description | string | false | | | The description of the event bus. |

### Test Event Pattern Match

| Parameter | Type | Required | Default | Constraints | Description |
|------|------|------|--------|------|------|
| Event | string | true | | | The event to test, which must be a JSON string. |
| EventPattern | string | true | | | The event pattern to test, which must be a JSON string. |

### Delete Event Targets

| Parameter | Type | Required | Default | Constraints | Description |
|------|------|------|--------|------|------|
| EventBusName | string | true | | | The name of the event bus. |
| RuleName | string | true | | | The name of the event rule. |
| TargetIds | array | false | | | The IDs of the event targets that you want to delete. |

### Create Event Targets

| Parameter | Type | Required | Default | Constraints | Description |
|------|------|------|--------|------|------|
| EventBusName | string | true | | | The name of the event bus. |
| RuleName | string | true | | | The name of the event rule. |
| Targets | array | true | | Each target must have an Id and Endpoint. | A list of target entries to be created. |

## Code Examples

### Create Event Rule - Python - All Regions

```python
import requests
import json

url = "https://123456789098****.eventbridge.cn-hangzhou.aliyuncs.com/openapi/createRule"
headers = {
    "Content-Type": "application/json;charset=UTF-8",
    "Authorization": "acs vZ3VL0SuJdHi****:Jo2PbT******azYAYoYslKLvWzg=",
    "x-eventbridge-version": "2020-04-01",
    "Date": "Sat, 18 Apr 2020 05:30:41 GMT"
}

payload = {
    "EventBusName": "default",
    "RuleName": "MNSRule",
    "Description": "Filter rule for MNS",
    "Status": "ENABLE",
    "filterPattern": "{\"source\": [{\"prefix\": \"acs.\"}],\"type\": [{\"prefix\":\"oss:ObjectReplication\"}],\"subject\":[{\"prefix\":\"acs:oss:cn-hangzhou:123456789098****:my-movie-bucket/\", \"suffix\":\".txt\"}]}",
    "EventTargets": [
        {
            "Id": "1",
            "Type": "acs.mns.queue",
            "Endpoint": "acs:mns:cn-hangzhou:123456789098****:queues/myqueue",
            "PushRetryStrategy": "BACKOFF_RETRY",
            "DeadLetterQueue": {
                "Arn": "acs:mns:cn-hangzhou:123456789098****:/queues/rule-deadletterqueue"
            },
            "ParamList": [
                {
                    "resourceKey": "queue",
                    "form": "CONSTANT",
                    "value": "myqueue"
                },
                {
                    "resourceKey": "body",
                    "form": "TEMPLATE",
                    "value": "{\"key\"=\"value\"}",
                    "template": "The value of ${key} is ${value}!"
                }
            ]
        }
    ]
}

response = requests.post(url, headers=headers, data=json.dumps(payload))
print(response.json())
```

### Delete Event Rule - Java - All Regions

```java
import com.aliyun.eventbridge.EventBridge;
import com.aliyun.eventbridge.EventBridgeClient;
import com.aliyun.eventbridge.models.Config;
import com.aliyun.eventbridge.models.DeleteRuleRequest;

public class deleteEventRuleSample {

    private EventBridge eventBridgeClient;

    public deleteEventRuleSample() {
        Config authConfig = new Config();
    authConfig.accessKeyId = "{accessKeyId}";
        authConfig.accessKeySecret = "{accessKeySecret}";
        authConfig.endpoint = "{endpoint}";
        eventBridgeClient = new EventBridgeClient(authConfig);
    }

    public void deleteEventRuleSample() {
        try {
            DeleteRuleRequest deleteEventRuleRequest = new DeleteRuleRequest();
            deleteEventRuleRequest.setRuleName("myRule");
            deleteEventRuleRequest.setEventBusName("mybus");
            eventBridgeClient.deleteRule(deleteEventRuleRequest);
            System.out.println("delete rule success : " + deleteEventRuleRequest.getEventBusName() + "/"
                    + deleteEventRuleRequest.getRuleName());
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        deleteEventRuleSample eventRuleSamples = new deleteEventRuleSample();
        try {
            eventRuleSamples.deleteEventRuleSample();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}
```

### Test Event Pattern Match - JSON Request - All Regions

```json
{
  "Event": "{\"source\":\"acs.oss\",\"type\":\"oss:ObjectCreated:PutObject\",\"subject\":\"acs:oss:cn-hangzhou:123456789098****:my-bucket/my-object.txt\"}",
  "EventPattern": "{\"source\":[{\"prefix\":\"acs.\"}],\"type\":[{\"prefix\":\"oss:ObjectCreated\"}]}"
}
```

### Create Event Targets - Go - All Regions

```go
package main

import (
    eventbridge "github.com/alibabacloud-go/eventbridge-sdk/eventbridge"
    console "github.com/alibabacloud-go/tea-console/client"
    util "github.com/alibabacloud-go/tea-utils/service"
    "github.com/alibabacloud-go/tea/tea"
)

/**
* Uses the CreateClient() function to initialize common request parameters.
 */
func CreateClient() (_result *eventbridge.Client, _err error) {
    config := &eventbridge.Config{}
    // Your AccessKey ID.
    config.AccessKeyId = tea.String("<accessKeyId>")
    // Your AccessKey secret.
    config.AccessKeySecret = tea.String("<accessKeySecret>")
    // Your endpoint.
    config.Endpoint = tea.String("<endpoint>")
    _result = &eventbridge.Client{}
    _result, _err = eventbridge.NewClient(config)
    return _result, _err
}

func CreateTargetsSample(client *eventbridge.Client) (_err error) {
    tryErr := func() (_e error) {
        defer func() {
            if r := tea.Recover(recover()); r != nil {
                _e = r
            }
        }()
        createTargetsRequest := &eventbridge.CreateTargetsRequest{}
        createTargetsRequest.EventBusName = tea.String("demo-bus")
        createTargetsRequest.RuleName = tea.String("myRule3")
        targetEntry := &eventbridge.TargetEntry{}
        targetEntry.Id = tea.String("1234")
        targetEntry.Endpoint = tea.String("http://www.example.com")
        list := []*eventbridge.TargetEntry{targetEntry}
        createTargetsRequest.Targets = list
        response, _err := client.CreateTargets(createTargetsRequest)
        if _err != nil {
            return _err
        }

        console.Log(tea.String("--------------------create targets success--------------------"))
        console.Log(util.ToJSONString(tea.ToMap(response)))

        return nil
    }()

    _err = tryErr
    if tryErr != nil {
        var error = &tea.SDKError{}
        if _t, ok := tryErr.(*tea.SDKError); ok {
            error = _t
        } else {
            error.SetErrMsg(tryErr.Error())
        }
        console.Log(error.Message)
    }
    return _err
}

func main() {
    client, _err := CreateClient()
    if _err != nil {
        panic(_err)
    }

    _err = CreateTargetsSample(client)
    if _err != nil {
        panic(_err)
    }
}
```

### List Event Rules - Python - All Regions

```python
# -*- coding: utf-8 -*-

from alibabacloud_eventbridge.client import Client as EventBridgeClient
from alibabacloud_event_bridge import models as event_bridge_models
from alibabacloud_tea_console.client import Client as ConsoleClient
from alibabacloud_tea_util.client import Client as UtilClient

class list_event_rules_sample(object):
    def __init__(self):
        pass

    @staticmethod
    def create_client():
        """
        Uses the create_client() function to initialize common request parameters.
        """
        config = event_bridge_models.Config(

        )
        # Your AccessKey ID.
        config.access_key_id = "<accessKeyId>"
        # Your AccessKey secret.
        config.access_key_secret = "<accessKeySecret>"
        # Your endpoint.
        config.endpoint = "<endpoint>"
        return EventBridgeClient(config)

    @staticmethod
    def list_event_rules_sample(client):
        try:
            list_rules_request = event_bridge_models.ListRulesRequest(
            )
            list_rules_request.event_bus_name = "demo-bus"
            response = client.list_rules(list_rules_request)
            ConsoleClient.log("--------------------list rules success--------------------")
            ConsoleClient.log(UtilClient.to_jsonstring(response.to_map()))
        except Exception as error:
            ConsoleClient.log(error.message)

    @staticmethod
    def main(args):
        client = list_event_rules_sample.create_client()
        list_event_rules_sample.list_event_rules_sample(client)

list_event_rules_sample.main("")
```

### Disable Event Rule - TypeScript - All Regions

```typescript
import EventBridge, * as $EventBridge from '@alicloud/eventbridge';
import Util from '@alicloud/tea-util';
import Console from '@alicloud/tea-console';
import * as $tea from '@alicloud/tea-typescript';

export default class Client {

    /**
     * Use the createClient() function to initialize common request parameters.
     */
    static async createClient(): Promise<EventBridge> {
        let config = new $EventBridge.Config({ });
        // Your AccessKey ID.
        config.accessKeyId = "<accessKeyId>";
        // Your AccessKey secret.
        config.accessKeySecret = "<accessKeySecret>";
        // Your endpoint.
        config.endpoint = "<endpoint>";
        return new EventBridge(config);
    }

    static async disableEventRuleSample(client: EventBridge): Promise<void> {
        try {
            let disableEventRuleRequest = new $EventBridge.DisableRuleRequest({ });
            disableEventRuleRequest.ruleName = "myRule";
            disableEventRuleRequest.eventBusName = "demo-bus";
            let resp = await client.disableRule(disableEventRuleRequest);
            Console.log("--------------------disable rule success--------------------");
            Console.log(Util.toJSONString($tea.toMap(resp)));
        } catch (error) {
            Console.log(error.message);
        }
    }

    static async main(args: string[]): Promise<void> {
        let client = await Client.createClient();
        await Client.disableEventRuleSample(client);
    }

}

Client.main(process.argv.slice(2));
```

### Update Event Rule - C# - All Regions

```csharp
using System;
using System.Collections.Generic;

using Tea;

namespace Alibabacloud.Sample
{
    public class Client
    {

        /**
         * Uses the CreateClient() function to initialize common request parameters.
         */
        public static AlibabaCloud.SDK.EventBridge.EventBridgeClient CreateClient()
        {
            AlibabaCloud.SDK.EventBridge.Models.Config config = new AlibabaCloud.SDK.EventBridge.Models.Config();
            // Your AccessKey ID.
            config.AccessKeyId = "<accessKeyId>";
            // Your AccessKey secret.
            config.AccessKeySecret = "<accessKeySecret>";
            // Your endpoint.
            config.Endpoint = "<endpoint>";
            return new AlibabaCloud.SDK.EventBridge.EventBridgeClient(config);
        }

        public static void UpdateEventRuleSample(AlibabaCloud.SDK.EventBridge.EventBridgeClient client)
        {
            try
            {
                AlibabaCloud.SDK.EventBridge.Models.UpdateRuleRequest updateEventRuleRequest = new AlibabaCloud.SDK.EventBridge.Models.UpdateRuleRequest();
                updateEventRuleRequest.RuleName = "myRule";
                updateEventRuleRequest.EventBusName = "demo-bus";
                updateEventRuleRequest.FilterPattern = "{\"source\":[\"acs.oss\"],\"type\":[\"oss:BucketQueried:GetBucketStat\"]}";
                client.UpdateRule(updateEventRuleRequest);
                Console.WriteLine("--------------------update rule success--------------------");
            }
            catch (TeaException error)
            {
                Console.WriteLine(error.Message);
            }
            catch (Exception _error)
            {
                TeaException error = new TeaException(new Dictionary<string, object>
                { { "message", _error.Message } });
                Console.WriteLine(error.Message);
            }
        }

        static void Main(string[] args)
        {
            AlibabaCloud.SDK.EventBridge.EventBridgeClient client = Client.CreateClient();
            Client.UpdateEventRuleSample(client);
            Console.ReadKey();
        }

    }
}
```

### Delete Event Targets - Bash/cURL - China Region

```bash
POST /openapi/deleteTargets HTTP/1.1
Host: 123456789098****.eventbridge.cn-hangzhou.aliyuncs.com
Date: Sat, 18 Apr 2020 05:30:41 GMT
x-eventbridge-version: 2020-04-01
Authorization: acs vZ3VL0SuJdHi****:Jo2PbT*****4azYAYoYslKLvWzg=
Content-type: application/json;charset=UTF-8
Content-Length: 26

{
    "EventBusName":"default",
    "RuleName":"myRule",
    "TargetIds":"target10"
}
```

## Response Format

```json
{
  "Message": "Remote error. requestId: [xxxx], error code: [xxx], message: [The target in event rule is invalid! Endpoint is xxx",
  "RequestId": "1AD6D598-7506-5D2C-81EA-30E3241A903A",
  "Data": {
    "RuleARN": "acs:eventbridge:cn-hangzhou:123456789098****:eventbus/default/rule/MNSRule"
  },
  "Code": "Success",
  "Success": true
}
```

**Key Fields**:
- `Data.RuleARN` — The Amazon Resource Name (ARN) of the created rule
- `RequestId` — Unique identifier for the API request
- `Code` — Status code indicating success or failure
- `Success` — Boolean indicating whether the operation succeeded

## Error Handling

| Error Code (Code) | Description (Description) | Recommended Action (Recommended Action) |
|---------------|--------------------|-----------------------------|
| 403 | ServiceNotEnable: The service is not enabled. Ensure that the EventBridge service is activated in your account. | Enable the EventBridge service in your Alibaba Cloud account |
| 400 | Bad Request – The request parameters are invalid or missing required fields. | Validate all required parameters and ensure proper JSON formatting |
| 404 | Not Found – The specified event bus or rule does not exist. | Verify the event bus name and rule name exist in your account |
| 500 | Internal Server Error – An unexpected error occurred on the server side. | Retry the request after a short delay; contact support if persistent |

### Rate Limits & Retry
- Standard rate limit: 100 QPS per account
- Free tier: 1000-10000 calls per month depending on operation type
- Implement exponential backoff for retry logic
- Check the `Retry-After` header if present in error responses

## Environment Requirements

- Set environment variables: `export ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id` and `export ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret`
- Install appropriate SDK packages:
  - Python: `pip install alibabacloud_eventbridge alibabacloud_tea_console alibabacloud_tea_util`
  - Java: `com.aliyun.eventbridge:2.0.0+`
  - Go: `github.com/alibabacloud-go/eventbridge-sdk@v1.0.0`
  - Node.js/TypeScript: `npm install @alicloud/eventbridge @alicloud/tea-util @alicloud/tea-console`

## FAQ

Q: How do I authenticate API requests to EventBridge?
A: Use your Alibaba Cloud AccessKey ID and AccessKey Secret to generate a signature for the Authorization header. The format is `Authorization: acs <AccessKeyId>:<Signature>` where the signature is calculated using HMAC-SHA1.

Q: What event pattern syntax is supported for filtering events?
A: EventBridge supports JSON-based patterns with operators like stringEqual, stringExpression, prefix matching, and suffix matching. You can use AND logic across different keys and OR logic across values within the same key.

Q: Can I temporarily disable a rule without deleting it?
A: Yes, you can disable a rule by setting its status to DISABLE using the UpdateRule API, or by calling the dedicated DisableRule operation. This stops event processing without losing the rule configuration.

Q: How many targets can I associate with a single rule?
A: You can associate up to 100 targets with a single event rule. Each target must have a unique ID within the rule.

Q: What happens when an event matches multiple rules?
A: EventBridge evaluates all rules in the event bus independently. If an event matches multiple rules, it will be delivered to all matching rule targets according to each rule's configuration.

## Pricing & Billing

### Billing Model
Per-request billing model where each API call counts as one request regardless of success or failure.

### Price Reference

| Tier/Model | Input Price | Output Price | Other Fees |
|-----------|---------|---------|---------|
| standard | 0.0001 / | 0.0001 / |

### Free Tier
Monthly free allowance of 1000-10,000 calls depending on the specific operation (rule creation typically has 1000 free calls, while some operations like target creation may have 10,000).

### Usage Limits
- Rate limits: 100 QPS per account
- FilterPattern maximum length: 8192 characters
- Maximum targets per rule: 100
- Maximum rules per event bus: varies by account quota

### Billing Notes
- Charges apply to both successful and failed API requests
- Free tier resets monthly
- Async operations are billed upon completion
- Failed requests still count toward your quota and billing