Redis Atomic Operations, Transactions, and Pipelining

Understand atomic operations, transactions, and pipelining, and distinguish correctness from batch efficiency.

🎯 Introduction

By the end of this article, you will be able to avoid lost counts with atomic increments, group related changes in transactions, and reduce network waits with pipelining.


🧱 Atomicity of Redis Commands

Atomicity here means that other clients' commands cannot interleave with the execution of a single command. Two commands sent consecutively by an application are still separate operations; another client can modify the data between them.

This matters when multiple requests modify the same data. If two requests both read 10 and then each writes 11, one increment is lost. Use Redis atomic commands for these changes.

This article uses Node.js 22.9.0, redis 5.9.0, and Redis 7.4.2. Add the following blocks to transactions.mjs in order, reusing the connection from the introduction:

transactions.mjs
import { redis } from './redis.mjs';

await redis.connect();
const counterKey = 'course:atomic:views';
await redis.del(counterKey);

🛠 INCR and Other Atomic Operations

INCR increments an integer, performing the read, increment, and write inside Redis and returning the new value. Concurrent clients cannot overwrite each other's increments by reading the same old value.

Use cases: counting visits or operations. Observe an increment by one followed by an increment by a specified amount:

transactions.mjs
console.log(await redis.incr(counterKey));
console.log(await redis.incrBy(counterKey, 3));

The outputs are 1 and 4. Missing keys start at 0; the second argument to incrBy is the increment. Use hIncrBy for Hash fields and zIncrBy for ranking scores; the principle is the same.

The value must represent an integer supported by Redis. Incrementing JSON text raises an error, and incrementing does not automatically set expiration.


🧰 Transactions with MULTI, EXEC, and WATCH

A Redis transaction queues a group of commands and submits them together. Once submitted, other clients' commands cannot interleave with that group's execution. MULTI starts collecting commands; EXEC submits the group and returns each command's result.

Use cases: related changes that must run consecutively, such as writing a Hash and setting its expiration. Prepare the exercise key:

transactions.mjs
const profileKey = 'course:atomic:profile';
await redis.del(profileKey);
const transaction = redis.multi();

multi() creates the group. Add two changes; they have not been sent for execution yet:

transactions.mjs
transaction.hSet(profileKey, { name: 'Lin' });
transaction.expire(profileKey, 60);

Submit the group and inspect the results:

transactions.mjs
console.log(await transaction.exec());
console.log(await redis.ttl(profileKey));

Starting with a missing key produces [1, 1]: one field was added and expiration was set successfully. The TTL is close to 60.

Redis transactions do not provide database-style rollback. If a command encounters a type error during execution, other valid commands may still execute. A failed transaction does not mean all data is unchanged.

WATCH monitors specified keys for changes. If a watched key changes between the start of monitoring and transaction submission, the transaction does not execute. WATCH does not lock the data; other clients can still modify watched keys.

Use cases: read an old value, calculate a new value in your program, and avoid overwriting intervening updates when submitting the change.

Create a dedicated connection in the same script to keep WATCH state separate from other requests:

transactions.mjs
import { WatchError } from 'redis';

const watched = redis.duplicate();
watched.on('error', error => console.error(error.message));
await watched.connect();
await redis.set('course:atomic:label', 'A');

Watch the key, read its old value, and simulate a change through another connection:

transactions.mjs
await watched.watch('course:atomic:label');
const label = await watched.get('course:atomic:label');
await redis.set('course:atomic:label', 'B');

Try submitting a result based on the old value:

transactions.mjs
try {
    await watched.multi().set('course:atomic:label', `${label}!`).exec();
} catch (error) {
    if (!(error instanceof WatchError)) throw error;
    console.log('The data changed; this update was not submitted');
} finally {
    await watched.close();
}

The conflict message is printed, and the key remains B. An application can reread and retry a bounded number of times, or return a conflict. WATCH state belongs to a connection. Concurrent HTTP requests need exclusive connections or a connection pool; do not interleave WATCH workflows on a shared connection. See node-redis transactions.


⚡ Batching Commands with Pipelining

Pipelining sends commands in a batch and receives their results afterward. The client need not wait for a reply after every command, reducing network waits across consecutive operations. It does not provide a transaction's uninterrupted execution guarantee.

Use cases: reading multiple independent keys or writing independent values in a batch. Send two writes together:

transactions.mjs
const pipeline = redis.multi();
pipeline.set('course:atomic:a', 'A');
pipeline.set('course:atomic:b', 'B');
console.log(await pipeline.execAsPipeline());

The output is ['OK', 'OK']. Although multi() collects the commands, execAsPipeline() does not wrap them in a Redis transaction.

Keep batch sizes bounded. Accumulating too many commands increases pressure on client, server, and network buffers. Pipelining does not make an individual slow command faster.


⚖️ Pipelining and Transactions Compared

RequirementChoice
Increment one value onceAn atomic command such as INCR
Execute a fixed group of commands consecutivelymulti() + exec()
Update based on a previously read valueCheck conflicts with WATCH, then submit a transaction
Read or write independent results in a batchPipelining

JavaScript's Promise.all does not provide transaction guarantees.

Close the connection and run the script:

transactions.mjs
await redis.close();
node transactions.mjs

❓ Questions and Answers

Q1: Can I immediately use a transaction's get result in a JavaScript condition?

No. Queued commands have not executed; results arrive after exec completes. Use WATCH for read-modify-write workflows. Short Lua scripts can also handle server-side conditional operations.

Q2: Can a transaction commit Redis and MySQL together?

No. It manages only Redis commands. Consistency across the two systems needs a separate design.

Q3: Can I replay the whole command group after a timeout?

Not without further handling. A timeout only means the client did not receive the result in time; the server may already have executed the commands. Replaying INCR increments again. Atomicity does not guarantee exactly-once execution of a business request.


🧪 Exercise

Combine List insertion and trimming in a transaction to keep only the three most recent records. Then use a pipeline to read two unrelated keys.

// Write your code here
// Hint: lPush, lTrim, exec, execAsPipeline

🎉 You now understand the boundaries of atomic operations, transactions, and pipelining!