Skip to content

Transaction

A transaction in Valkey GLIDE allows you to execute a group of commands in a single, atomic step. This ensures that all commands in the transaction are executed sequentially and without interruption. See Valkey Transactions.

This is equivalent to the Valkey commands MULTI / EXEC.

There are two primary modes for handling transactions in Glide:

  1. Standalone Mode: Use the Transaction class.
  2. Cluster Mode: Use the ClusterTransaction class.

Transaction objects can be reused. If you need to execute a particular group of commands multiple times, you can simply resend the same transaction object.

Here’s a simple example demonstrating how to create and execute a transaction in standalone mode:

import {Transaction} from "@valkey/valkey-glide";
// Initialize a transaction object
const transaction = new Transaction();
// Add commands to the transaction
transaction.set('key', 'value');
transaction.select(1); // Standalone command
transaction.get('key');
// Execute the transaction
const result = await client.exec(transaction);
console.log(result); // Output: [OK, OK, null]

Valkey GLIDE supports command chaining within a transaction, allowing for a more concise and readable code. Here’s how you can use chaining in transactions:

import {ClusterTransaction} from "@valkey/valkey-glide";
// Initialize a cluster transaction object
const clusterTransaction = new ClusterTransaction();
// Chain commands
clusterTransaction.set('key', 'value').get('key')
// Execute the transaction
const result = await client.exec(clusterTransaction);
console.log(result); // Output: [OK, 'value']

Cluster Mode Considerations: When using ClusterTransaction, all keys in the transaction must be mapped to the same slot.

Creating a Transaction: Initialize the Transaction or ClusterTransaction object.

import {Transaction, ClusterTransaction} from "@valkey/valkey-glide";
const transaction = new Transaction(); // For standalone mode
const clusterTransaction = new ClusterTransaction(); // For cluster mode

Adding Commands: Use the transaction object to queue up the desired commands.

transaction.set('key', 'value');
transaction.get('key');

Executing the Transaction: Use the exec method of the Valkey GLIDE client to execute the transaction.

await client.exec(transaction);

Handling Results: The result of the transaction execution will be a list of responses corresponding to each command in the transaction.

const result = await client.exec(transaction)
console.log(result); // Output: [OK, 'value']