100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Redis

Redis Transactions: MULTI/EXEC

Understand how Redis groups commands into atomic transactions using MULTI, EXEC, DISCARD, and optimistic locking with WATCH.

Key ManagementIntermediate10 min readJul 10, 2026
Analogies

What MULTI/EXEC Actually Guarantees

A Redis transaction begins with MULTI, which puts the connection into a queuing state: every subsequent command is not executed immediately but appended to a queue, and Redis replies QUEUED to each one. Calling EXEC then runs every queued command sequentially and atomically as a single unit, with no other client's commands interleaved in between, because Redis is single-threaded for command execution. This gives you isolation (no interleaving) and atomicity of execution order, but it is important to understand this is not the same guarantee as a relational database's ACID transaction, since Redis will not roll back earlier commands in the batch if a later command fails at runtime.

🏏

Cricket analogy: MULTI/EXEC is like a captain locking in an entire bowling change and field placement plan before the umpire signals play, so the whole sequence executes as one uninterrupted passage of play with no other team's action slipping in between overs.

bash
MULTI
QUEUED
DECRBY account:alice:balance 100
QUEUED
INCRBY account:bob:balance 100
QUEUED
EXEC
1) (integer) 400
2) (integer) 600

# If a queued command has a syntax error, EXEC is aborted entirely:
MULTI
QUEUED
SET foo bar
QUEUED
NOTACOMMAND
(error) ERR unknown command 'NOTACOMMAND'
EXEC
(error) EXECABORT Transaction discarded because of previous errors.

Runtime Errors Do Not Roll Back

Redis distinguishes between two failure classes. A syntax or queuing error (an unknown command, wrong number of arguments) is caught before EXEC even runs, and Redis aborts the entire transaction with EXECABORT, executing nothing. But a runtime error, such as running INCR on a key that holds a string value, is only detected while EXEC is actually executing that specific command — Redis will still run every other queued command in the batch and simply return an error for the failing one within the results array, exactly the behavior a relational database's transaction rollback is designed to prevent.

🏏

Cricket analogy: This is like a pre-approved batting order that gets rejected entirely if a name is misspelled before the match starts (caught early, nothing happens), versus a batter getting run out mid-innings — the rest of the batting order still proceeds, it doesn't cancel the whole innings.

Never assume MULTI/EXEC gives you rollback-on-failure semantics like a SQL transaction. If command 3 of 5 in your transaction fails at runtime, commands 1, 2, 4, and 5 have already been applied and stay applied. Your application logic must be designed to tolerate partial application, or you must validate inputs before queuing commands to avoid runtime errors in the first place.

Optimistic Locking with WATCH

WATCH key marks a key for optimistic locking: if any other client modifies a watched key between your WATCH call and your EXEC call, Redis aborts your transaction automatically, EXEC returns a null reply, and none of your queued commands are applied. This gives you a classic check-and-set pattern, common for implementing things like a balance transfer that first reads a balance, checks it's sufficient, then commits the debit — all without needing a heavier server-side locking mechanism. The typical pattern is WATCH the relevant keys, read their current values with GET/HGET outside the transaction, decide what to queue based on those values, then MULTI, queue the writes, and EXEC; on a null reply from EXEC, the whole read-decide-write cycle is retried.

🏏

Cricket analogy: WATCH is like a third umpire flagging that they'll review a run-out decision only if the replay footage hasn't been altered since they started reviewing — if the footage changes mid-review, they discard the decision and ask for a fresh review from scratch.

python
import redis

r = redis.Redis()

def transfer(from_key, to_key, amount):
    with r.pipeline() as pipe:
        while True:
            try:
                pipe.watch(from_key)
                balance = int(pipe.get(from_key) or 0)
                if balance < amount:
                    pipe.unwatch()
                    raise ValueError("Insufficient balance")
                pipe.multi()
                pipe.decrby(from_key, amount)
                pipe.incrby(to_key, amount)
                pipe.execute()  # raises WatchError if from_key changed
                break
            except redis.WatchError:
                continue  # someone else modified from_key, retry

transfer("account:alice:balance", "account:bob:balance", 100)

When to Reach for Lua Scripts Instead

MULTI/EXEC queues commands client-side and sends them together, but it cannot make branching decisions based on a value read mid-transaction, since all commands are queued blindly before any of them execute. When your logic needs conditional branching (read a value, then decide which of several different commands to run based on that value, all atomically), a Lua script executed with EVAL or EVALSHA is the better tool, because the entire script runs atomically on the server with full access to intermediate results, no round trips, and no risk of another client's write landing in the middle of your decision logic the way it theoretically could between separate client-side round trips even with WATCH.

🏏

Cricket analogy: This is like the difference between a captain pre-committing a fixed bowling order regardless of how the innings unfolds (MULTI/EXEC) versus giving the on-field vice-captain full authority to adapt bowling changes in real time based on how each over actually plays out (Lua script) — the latter can react to intermediate outcomes, the former can't.

A Lua script run via EVAL is itself atomic for the same reason MULTI/EXEC is: Redis's single-threaded command execution means no other command can interleave while the script runs. This makes Lua scripting the go-to choice for atomic read-then-conditionally-write logic that's too dynamic for MULTI/EXEC's blind command queuing.

  • MULTI starts queuing commands (each replies QUEUED); EXEC runs the whole queue atomically and without interleaving from other clients.
  • Syntax/queuing errors abort the entire transaction before EXEC runs (EXECABORT); no queued command executes.
  • Runtime errors (e.g. INCR on a string) do not roll back other commands in the batch — everything else still executes.
  • WATCH implements optimistic locking: if a watched key changes before EXEC, the transaction aborts and EXEC returns null.
  • The standard pattern is WATCH, read values, decide what to queue, MULTI, queue writes, EXEC, and retry on null.
  • DISCARD cancels a queued transaction before EXEC without running any of the queued commands.
  • For logic requiring conditional branching on values read mid-transaction, a Lua script (EVAL/EVALSHA) is the correct tool, not MULTI/EXEC.

Practice what you learned

Was this page helpful?

Topics covered

#Redis#RedisStudyNotes#Database#RedisTransactionsMULTIEXEC#Transactions#MULTI#EXEC#Actually#StudyNotes#SkillVeris

Frequently Asked Questions

21 categories · pick one to explore

Where can I get free study notes for programming and tech subjects?
SkillVeris offers completely free study notes covering programming and tech subjects, with no signup fees or paywalls. The notes are structured by course and topic, written for quick understanding, and enriched with the Learn Through Hobbies analogy method, so you can revise concepts through cricket, music, gaming, cooking and more.
Are SkillVeris study notes good for exam revision?
Yes, the study notes are designed for efficient revision: each topic answers its heading immediately, keeps explanations concise, and links to related glossary terms and cheat sheets. Students preparing for university exams or certification tests use them as quick revision notes because they distil concepts without the padding of full textbooks.
What subjects do the free study notes cover?
The study notes span the platform's main domains, including AI and machine learning, Python and programming, web development, DevOps, cloud, security and databases. Coverage mirrors the 37 live courses, so notes exist for the topics you are actually studying, and new note sets are added as courses launch.
How are SkillVeris study notes different from regular textbooks?
The notes are answer-first, concise and free, whereas textbooks are long and often expensive. Each section explains one concept directly, then reinforces it through selectable hobby analogies like cricket or cooking. Notes also cross-link to the glossary, blog and cheat sheets, letting you jump to related material instantly instead of flipping pages.
Can I use the developer study material without creating an account?
The study notes are free to access, and SkillVeris does not charge anything for its developer study material at any point. Browsing notes is straightforward from the Study Notes section, and if you want progress tracking, certificates and AI Mentor conversations tied to your learning, a free account unlocks those extras.
Do the study notes explain concepts with analogies?
Yes, this is a signature SkillVeris feature. Study notes use the Learn Through Hobbies method, explaining technical concepts through analogies from twelve domains including cricket, music, gaming, photography, travel, movies, fitness, chess, cooking, finance, business and sports. You can switch the analogy domain instantly to whichever hobby makes the concept click.
Are the revision notes suitable for last-minute exam preparation?
Yes, revision notes on SkillVeris work well for last-minute preparation because every section states the answer in its first sentences, so skimming is genuinely effective. Pair them with the relevant cheat sheet for formulas and syntax, and use the glossary for any unfamiliar term you meet while cramming.
Is there free study material for AI and machine learning?
Yes, SkillVeris provides free study notes across its AI and ML catalogue, covering Python for AI, deep learning frameworks like PyTorch and TensorFlow, Hugging Face Transformers, Large Language Models, RAG, AI agents and MLOps. All of it is free, making it a strong resource for Indian students and global learners alike.
Can beginners understand the study notes, or are they for experts?
Beginners can absolutely use them. The notes are written in plain language, define terms as they appear, and lean on hobby analogies to make abstract ideas concrete. Difficulty scales with the underlying course level, so beginner-course notes stay gentle while advanced-course notes go deeper, and the glossary supports you throughout.
How do study notes connect with SkillVeris courses?
Study notes are organised by course and topic, so they map directly to the structured courses and their 24–40-lesson curriculum. Many learners study a lesson first, then use the matching notes for revision before module assessments and the final exam, where 80 percent is required to pass and earn the certificate.
Are there study notes for Python specifically?
Yes, Python is well covered through notes tied to the Python-focused courses, including Python for AI and ML. Topics span fundamentals through applied machine learning usage. You can reinforce the notes with Python practice in Code Lab, which runs code in your browser with no installation required.
Do the study notes include code examples?
Yes, study notes include code examples wherever a concept is best shown in code, alongside explanations, key points and analogies. Reading a snippet in the notes and then reproducing it yourself in Code Lab is an effective loop, since Code Lab lets you run code in the browser across six languages.
How often is new study material added to SkillVeris?
Study material grows alongside the course catalogue. Whenever new courses join the platform's 37 live courses, matching study notes, glossary entries and cheat sheets are added so the resources stay in sync. Existing notes are also refined over time, so it is worth revisiting topics you studied earlier.
Can I use SkillVeris notes to prepare for technical interviews?
Yes, the notes make excellent interview revision because they compress each concept into direct, answer-first explanations, which mirrors how you should answer interview questions. Combine them with the SkillVeris interview questions feature, which includes readiness scoring, to test whether your revision has actually made you interview-ready.
Are the study notes mobile-friendly for studying on the go?
Yes, the study notes are built to load fast and read comfortably on mobile devices, so you can revise during a commute or between classes. Sections are short and answer-first, which suits small screens, and analogy switching works on mobile too, letting you study anywhere without carrying books.
What is the difference between study notes and cheat sheets?
Study notes explain concepts in depth with context, examples and analogies, making them ideal for learning and revision. Cheat sheets are compact quick-reference summaries of syntax, commands and key facts, ideal once you already understand a topic. Most learners study the notes first, then keep the cheat sheet handy while coding.
Do study notes help if I am stuck on a course lesson?
Yes, reading the matching study notes often clarifies a lesson because the same concept is explained from a different angle, frequently with a different analogy. If you are still stuck, ask the AI Mentor, which answers 24/7 at Quick, Detailed or Deep-dive depth until the idea genuinely makes sense.
Is there free study material for DevOps and cloud topics?
Yes, SkillVeris carries free study notes for DevOps and cloud topics as part of its coverage across 37 live courses. The material suits learners following the DevOps Engineer or Cloud Engineer paths, and it links to related glossary terms and cheat sheets so you can revise the whole toolchain in one place.
Can school or college students in India use these notes for projects?
Yes, students across India and worldwide use SkillVeris notes for coursework, projects and exam preparation, and everything is free, which matters for student budgets. The notes explain concepts clearly enough to cite in project reports, and Code Lab lets you prototype the project code directly in your browser.
How should I combine study notes with other SkillVeris resources?
A proven loop: learn from a course lesson, revise with the matching study notes, look up unfamiliar terms in the glossary, keep the cheat sheet open while practising in Code Lab, and quiz yourself with interview questions. The AI Mentor fills any remaining gaps 24/7, at whatever depth you need.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse