Publishing is great for sending one message at a time, but sometimes you want to send a batch of messages at once.

This can be useful to send messages to a single or multiple destinations. QStash provides the batch endpoint to help you with this.

If the format of the messages are valid, the response will be an array of responses for each message in the batch. When batching topics, the response will be an array of responses for each destination in the topic. If one message fails to be sent, that message will have an error response, but the other messages will still be sent.

Batching messages with destinations

You can also send messages to the same destination!
curl -XPOST https://qstash.upstash.io/v2/batch \
    -H 'Authorization: Bearer XXX' \
    -H "Content-type: application/json" \
    -d '
     [
      {
        "destination": "https://example.com/destination1"
      },
      {
        "destination": "https://example.com/destination2"
      }
     ]'

Batching messages with topics

If you have a topic, you can batch send with the topic as well.

curl -XPOST https://qstash.upstash.io/v2/batch \
    -H 'Authorization: Bearer XXX' \
    -H "Content-type: application/json" \
    -d '
     [
      {
        "destination": "mytopic"
      },
      {
        "destination": "https://example.com/destination2"
      }
     ]'

Batching messages with headers and body

You can provide custom headers and a body for each message in the batch.

curl -XPOST https://qstash.upstash.io/v2/batch   -H "Authorization: Bearer XXX" \
    -H "Content-Type: application/json" \
    -d '
    [
      {
          "destination": "mytopic",
          "headers":{
            "Upstash-Delay":"5s",
            "Upstash-Forward-Hello":"123456"
          },
          "body": "Hello World"
      },
      {
          "destination": "https://example.com/destination1",
          "headers":{
            "Upstash-Delay":"7s",
            "Upstash-Forward-Hello":"789"
          }
      },
      {
          "destination": "https://example.com/destination2",
          "headers":{
            "Upstash-Delay":"9s",
            "Upstash-Forward-Hello":"again"
          }
      }
    ]'

The response for this will look like

[
  [
    {
      "messageId": "msg_...",
      "url": "https://mytopic-endpoint1.com"
    },
    {
      "messageId": "msg_...",
      "url": "https://mytopic-endpoint2.com"
    }
  ],
  {
    "messageId": "msg_..."
  },
  {
    "messageId": "msg_..."
  }
]