JavaScript APIs
Cloudflare Queues is integrated with Cloudflare Workers. To send and receive messages, you must use a Worker.
A Worker that can send messages to a Queue is a producer Worker, while a Worker that can receive messages from a Queue is a consumer Worker. It is possible for the same Worker to be a producer and consumer, if desired.
In the future, we expect to support other APIs, such as HTTP endpoints to send or receive messages. To report bugs or request features, go to the Cloudflare Community Forums ↗. To give feedback, go to the #queues ↗ Discord channel.
Producer
These APIs allow a producer Worker to send messages to a Queue.
An example of writing a single message to a Queue:
The Queues API also supports writing multiple messages at once:
Queue
A binding that allows a producer to send messages to a Queue.
interfaceQueue<Body=unknown>{send(body:Body,options?:QueueSendOptions):Promise<QueueSendResult>;sendBatch(messages:Iterable<MessageSendRequest<Body>>,options?:QueueSendBatchOptions):Promise<QueueSendResult>;metrics():Promise<QueueMetrics>;}-
send(body: unknown, options?: {contentType?: QueuesContentType })Promise<QueueSendResult>- Sends a message to the Queue. The body can be any type supported by the structured clone algorithm ↗, as long as its size is less than 128 KB.
- When the promise resolves, the message is confirmed to be written to disk.
- Returns a QueueSendResult containing realtime metrics about the queue.
-
sendBatch(messages: Iterable<MessageSendRequest<unknown>>, options?: QueueSendBatchOptions)Promise<QueueSendBatchResult>- Sends a batch of messages to the Queue. Each item in the provided Iterable ↗ must be supported by the structured clone algorithm ↗. A batch can contain up to 100 messages, though items are limited to 128 KB each, and the total size of the array cannot exceed 256 KB.
- The optional
optionsparameter can be used to apply settings (such asdelaySeconds) to all messages in the batch. See QueueSendBatchOptions. - When the promise resolves, the messages are confirmed to be written to disk.
-
metrics()Promise<QueueMetrics>- Returns realtime QueueMetrics for the queue.
MessageSendRequest
A wrapper type used for sending message batches.
interfaceMessageSendRequest<Body=unknown>{body:Body;contentType?:QueueContentType;delaySeconds?:number;}-
bodyunknown- The body of the message.
- The body can be any type supported by the structured clone algorithm ↗, as long as its size is less than 128 KB.
-
contentTypeQueueContentType- The explicit content type of a message so it can be previewed correctly with the List messages from the dashboard feature. Optional argument.
- See QueuesContentType for possible values.
-
delaySecondsnumber- The number of seconds to delay a message for within the queue, before it can be delivered to a consumer.
- Must be an integer between 0 and 86400 (24 hours).
QueueSendOptions
Optional configuration that applies when sending a message to a queue.
-
contentTypeQueuesContentType- The explicit content type of a message so it can be previewed correctly with the List messages from the dashboard feature. Optional argument.
- As of now, this option is for internal use. In the future,
contentTypewill be used by alternative consumer types to explicitly mark messages as serialized so they can be consumed in the desired type. - See QueuesContentType for possible values.
-
delaySecondsnumber- The number of seconds to delay a message for within the queue, before it can be delivered to a consumer.
- Must be an integer between 0 and 86400 (24 hours). Setting this value to zero will explicitly prevent the message from being delayed, even if there is a global (default) delay at the queue level.
QueueSendBatchOptions
Optional configuration that applies when sending a batch of messages to a queue.
-
delaySecondsnumber- The number of seconds to delay messages for within the queue, before it can be delivered to a consumer.
- Must be a positive integer.
QueuesContentType
A union type containing valid message content types.
// Default: jsontypeQueuesContentType="text"|"bytes"|"json"|"v8";- Use
"json"to send a JavaScript object that can be JSON-serialized. This content type can be previewed from the Cloudflare dashboard ↗. Thejsoncontent type is the default. - Use
"text"to send aString. This content type can be previewed with the List messages from the dashboard feature. - Use
"bytes"to send anArrayBuffer. This content type cannot be previewed from the Cloudflare dashboard ↗ and will display as Base64-encoded. - Use
"v8"to send a JavaScript object that cannot be JSON-serialized but is supported by structured clone ↗ (for exampleDateandMap). This content type cannot be previewed from the Cloudflare dashboard ↗ and will display as Base64-encoded.
If you specify an invalid content type, or if your specified content type does not match the message content's type, the send operation will fail with an error.
QueueSendResult
The result of a successful send operation.
interfaceQueueSendResult{metadata:{metrics:QueueMetrics;};}-
metadataobject- Contains metadata about the queue after the send operation.
-
metadata.metricsQueueMetrics- Realtime metrics for the queue. See QueueMetrics.
QueueMetrics
Realtime metrics for a queue.
interfaceQueueMetrics{backlogCount:number;backlogBytes:number;oldestMessageTimestamp:number;}-
backlogCountnumber- The number of messages currently in the queue.
-
backlogBytesnumber- The total size of messages in the queue, in bytes.
-
oldestMessageTimestampnumber- The timestamp (in milliseconds since epoch) of the oldest message in the queue.
Consumer
These APIs allow a consumer Worker to consume messages from a Queue.
To define a consumer Worker, add a queue() function to the default export of the Worker. This will allow it to receive messages from the Queue.
By default, all messages in the batch will be acknowledged as soon as all of the following conditions are met:
- The
queue()function has returned. - If the
queue()function returned a promise, the promise has resolved. - Any promises passed to
waitUntil()have resolved.
If the queue() function throws, or the promise returned by it or any of the promises passed to waitUntil() were rejected, then the entire batch will be considered a failure and will be retried according to the consumer's retry settings.
The env and ctx fields are as documented in the Workers documentation.
TypeScript message types
You can type queue messages with Queue<T> on the producer and ExportedHandler<Env, T> on the consumer.
typeMyMessage={id:string;};interfaceEnv{MY_QUEUE:Queue<MyMessage>;}exportdefault{asyncqueue(batch){for (constmessageofbatch.messages) {console.log(message.body.id);}},}satisfiesExportedHandler<Env,MyMessage>;For primitive messages, use Queue<number> or satisfies ExportedHandler<Env, number>. If you do not specify a type, message.body is unknown.
Or alternatively, a queue consumer can be written using the (deprecated) service worker syntax:
addEventListener('queue',(event)=>{event.waitUntil(handleMessages(event));});In service worker syntax, event provides the same fields and methods as MessageBatch, as defined below, in addition to waitUntil() ↗.
MessageBatch
A batch of messages that are sent to a consumer Worker.
interfaceMessageBatch<Body=unknown>{readonlyqueue:string;readonlymessages:readonlyMessage<Body>[];ackAll():void;retryAll(options?:QueueRetryOptions):void;}-
queuestring- The name of the Queue that belongs to this batch.
-
messagesMessage[]- An array of messages in the batch. Ordering of messages is best effort -- not guaranteed to be exactly the same as the order in which they were published.
-
ackAll()void- Marks every message as successfully delivered, regardless of whether your
queue()consumer handler returns successfully or not.
- Marks every message as successfully delivered, regardless of whether your
-
retryAll(options?: QueueRetryOptions)void- Marks every message to be retried in the next batch.
- Supports an optional
optionsobject.
Message
A message that is sent to a consumer Worker.
interfaceMessage<Body=unknown>{readonlyid:string;readonlytimestamp:Date;readonlybody:Body;readonlyattempts:number;ack():void;retry(options?:QueueRetryOptions):void;}-
idstring- A unique, system-generated ID for the message.
-
timestampDate- A timestamp when the message was sent.
-
bodyunknown- The body of the message.
- The body can be any type supported by the structured clone algorithm ↗, as long as its size is less than 128 KB.
-
attemptsnumber- The number of times the consumer has attempted to process this message. Starts at 1.
-
ack()void- Marks a message as successfully delivered, regardless of whether your
queue()consumer handler returns successfully or not.
- Marks a message as successfully delivered, regardless of whether your
-
retry(options?: QueueRetryOptions)void- Marks a message to be retried in the next batch.
- Supports an optional
optionsobject.
QueueRetryOptions
Optional configuration when marking a message or a batch of messages for retry.
interfaceQueueRetryOptions{delaySeconds?:number;}-
delaySecondsnumber- The number of seconds to delay a message for within the queue, before it can be delivered to a consumer.
- Must be a positive integer.
-
When the promise resolves, the messages are written to disk.
- Returns a QueueSendResult containing realtime metrics about the queue.
