DEV Community

Cover image for SQS Fair Queues with AWS EventBridge
Robert Slootjes
Robert Slootjes

Posted on

SQS Fair Queues with AWS EventBridge

A while ago AWS introduced Fair Queues, a new feature for SQS. I was immediately excited and started testing this using the SDK it worked really well:

import {
  SQSClient,
  SendMessageCommand,
} from '@aws-sdk/client-sqs';

const sqsClient = new SQSClient();
await sqsClient.send(
  new SendMessageCommand({
    QueueUrl: 'https://sqs.eu-west-1.amazonaws.com/123/fair-queue-demo',
    MessageBody: JSON.stringify({
      foo: 'bar',
    }),
    MessageGroupId: 'mybrand',
  }),
);
Enter fullscreen mode Exit fullscreen mode

The message MessageGroupId attribute has a value of mybrand as expected:

{
    "body": "{\"foo\":\"bar\"}",
    "attributes": {
        "ApproximateReceiveCount": "1",
        "SentTimestamp": "1764775946158",
        "MessageGroupId": "mybrand"
    }
}
Enter fullscreen mode Exit fullscreen mode

EventBridge

After the announcement of Fair Queues I tried to make it work with EventBridge since we use this almost everywhere. Passing the MessageGroupId dynamically was not possible unfortunately yet when Fair Queues was first released. However recently it was announced that the MessageGroupId can now be passed in EventBridge SQS Targets so I decided to give it another try:

import { 
  EventBridgeClient,
  PutEventsCommand,
} from '@aws-sdk/client-eventbridge';

const eventBridgeClient = new EventBridgeClient();
await eventBridgeClient.send(new PutEventsCommand({
  Entries: [{
    Source: 'myapp',
    DetailType: 'fair-queue-demo',
    Detail: JSON.stringify({
      brand: 'mybrand',
      foo: 'bar',
    })
  }]
}));
Enter fullscreen mode Exit fullscreen mode

In combination with this rule:

FairQueueDemoRule:
  Type: AWS::Events::Rule
  Properties:
    EventPattern:
      source:
        - myapp
      detail-type:
        - fair-queue-demo
    State: ENABLED
    Targets:
      - Id: FairQueueDemo
        Arn: !GetAtt FairQueueDemo.Arn
        SqsParameters:
          MessageGroupId: $.detail.brand
Enter fullscreen mode Exit fullscreen mode

And now it will actually set the MessageGroupId based on the contents of the detail object sent to EventBridge:

{
    "body": "{\"version\":\"0\",\"id\":\"90a484f2-d2e2-2ff2-f8b2-3b64a4538721\",\"detail-type\":\"fair-queue-demo\",\"source\":\"myapp\",\"time\":\"2025-12-03T15:21:16Z\",\"region\":\"eu-west-1\",\"resources\":[],\"detail\":{\"brand\":\"mybrand\",\"foo\":\"bar\"}}",
    "attributes": {
        "ApproximateReceiveCount": "1",
        "SentTimestamp": "1764775276763",
        "MessageGroupId": "mybrand"
    }
}
Enter fullscreen mode Exit fullscreen mode

As you can see, the MessageGroupId is set to mybrand as expected 🎉

Top comments (0)