Using AWS Step Functions To Schedule Or Delay SNS Message Publication

with no AWS Lambda function required

A co-worker at Archer asked if there was a way to schedule messages published to an Amazon SNS topic.

I know that scheduling messages to SQS queues is possible to some extent using the DelaySeconds message timer, which allows postponing visibility in the queue up to 15 minutes, but SNS does not currently have native support for delays.

However, since AWS Step Functions has built-in integration with SNS, and since it also has a Wait state that can schedule or delay execution, we can implement a fairly simple Step Functions state machine that puts a delay in front of publishing a message to an SNS topic, without any AWS Lambda code.

Overview

This article uses an AWS CloudFormation template to create a sample AWS stack with one SNS topic and one Step Functions state machine with two states.

AWS architecture diagram

This is the CloudFormation template, if you’d like to review it:

CloudFormation template: aws-sns-delayed

Here is the Step Functions state machine definition from the above CloudFormation template:

{
  "StartAt": "Delay",
  "Comment": "Publish to SNS with delay",
  "States": {
    "Delay": {
      "Type": "Wait",
      "SecondsPath": "$.delay_seconds",
      "Next": "Publish to SNS"
    },
    "Publish to SNS": {
      "Type": "Task",
      "Resource": "arn:aws:states:::sns:publish",
      "Parameters": {
        "TopicArn": "${SNSTopic}",
        "Subject.$": "$.subject",
        "Message.$": "$.message"
      },
      "End": true
    }
  }
}

The “Delay” state waits for “delay_seconds” provided in the input to the state machine execution (as we’ll see below).

The “Publish to SNS” task uses the Step Functions integration with SNS to call the publish API directly with the parameters listed, some of which are also passed in to the state machine execution.

Now let’s take it for a spin!