Skip to main content
Batch operations allow multiple updates to be grouped into a single channel message and applied atomically. It ensures that all operations in a batch either succeed together or are discarded entirely. Batching is essential when multiple related updates to channel objects must be applied as a single atomic unit, for example, when application logic depends on multiple objects being updated simultaneously. Batching ensures that all operations in the batch either succeed or fail together.

Create a batch context

To batch object operations together, use the batch() method on a PathObject or Instance. This method accepts a callback function that receives a batch context that allows you to construct operations. Ably publishes these operations together as a single channel message. If an error occurs publishing the batched operations, all operations are discarded, preventing partial updates and ensuring atomicity. Call batch() on a PathObject to group operations on that path:
You can only call batch() on an PathObject whose path resolves to a LiveMap or LiveCounter instance:
You can also call batch() on an Instance to batch operations on that specific object:

Create objects in a batch

You can create new objects inside a batch using LiveMap.create() and LiveCounter.create(). This allows you to atomically create and assign multiple objects in a single operation:
Creating objects inside a batch ensures that all objects are created and assigned as a single atomic operation, preventing inconsistent intermediate states. Navigate to nested objects using the get() method on the batch context. Navigating a batch context with get() has the same behaviour as navigating an Instance:

Cancel a batch

To explicitly cancel a batch before it is applied, throw an error inside the batch function. This prevents any queued operations from being applied:

Understand batch context behavior

The batch context has the same API as Instance, except for batch() itself, but all mutation methods are synchronous and queue operations instead of sending them immediately. After the callback completes, all queued operations are sent together in a single channel message.
Since the batch callback is synchronous, you can read current values inside a batch context without intermediate updates from other clients being applied between reads:
Operations on a batch context are not applied until they are all published, so you cannot read back data written inside the batch context callback:
The batch context object cannot be used outside the callback function. Attempting to do so results in an error:
When a batch operation is applied, the subscription is notified synchronously and sequentially for each operation included in the batch: