Sub topic 8
What happens inside: undo and redo
This chapter assumes you can run basic SQL and PL/SQL, and that you know what COMMIT, ROLLBACK, and SAVEPOINT do from the earlier chapters. Here you will see the machinery behind them: how Oracle records changes in undo and redo, and why a COMMIT is fast while a large ROLLBACK can be slow.
Two records for two jobs
Every change to a table block produces two kinds of change records. They serve opposite purposes.
| Row | Undo | Redo |
|---|---|---|
| Question it answers | How do I put this back the way it was? | How do I repeat this change? |
| Used by | ROLLBACK, read consistency, flashback queries | Instance recovery, media recovery, standby databases |
| Stored in | The undo tablespace, in undo segments | The redo log buffer, then the online redo log files |
| Lifetime | Needed while the transaction is active, and kept for a while after it ends | Needed until the change is safely in the data files and archived (if archiving is on) |
Undo is about the past: the "before image" of a changed row. Redo is about the future: a description of the change that can be replayed after a crash.
The undo data is itself protected by redo. A change to an undo block also generates redo. After a crash, Oracle can therefore rebuild the undo as well as the data.
What an UPDATE does step by step
Take the transfer from the earlier chapters:
UPDATE accounts SET balance = balance - 100 WHERE id = 1;Oracle works through these steps for the row with id = 1.
- It finds the data block in the buffer cache, reading it from disk if needed.
- It locks the row and records that lock in the block's transaction slot (the ITL entry).
- It writes the old value of
balance(1000) into an undo block, in the undo segment assigned to your transaction. - It changes the row in the data block in memory (1000 becomes 900). The block is now "dirty".
- It writes redo entries to the redo log buffer. One describes the undo change and one describes the data change.
Notice what does not happen. The dirty data block is not written to disk, and the redo is not necessarily on disk yet either. Oracle writes data blocks lazily, in the background.
Why COMMIT is fast
Because redo describes every change, Oracle does not need to write the data blocks to make a commit durable. It only needs the redo on disk. The sequence at COMMIT is short:
- Oracle assigns a system change number (SCN) to the commit. The SCN is a counter that orders all changes in the database.
- It writes a commit record into the redo log buffer.
- The log writer process (LGWR) writes the buffered redo, up to and including the commit record, to the online redo log files.
- Your session gets the message "Commit complete."
- The row locks are released.
The cost of a COMMIT therefore depends on the log file write, not on how many rows you changed. Committing 10 rows and committing 10 million rows both end with a single commit record. The 10 million row changes still had to produce redo while the transaction ran, but that redo was being flushed in the background as the buffer filled.
The undo is not discarded at commit. It stays in the undo segment, marked as no longer needed by an active transaction. Oracle keeps it for the undo retention period if space allows, because queries that started earlier may still need it (see the next section).
Why ROLLBACK can be slow
ROLLBACK is the reverse. Oracle must physically undo each change by reading your undo records and applying them, newest first. Each undone change is itself a change to a data block, so it also generates redo.
This leads to a useful rule of thumb. A transaction that took ten minutes to change 10 million rows may need a similar amount of time to roll back. A commit takes the same short time either way, while the cost of a rollback grows with the amount of work to undo.
You can see the size of an open transaction in V$TRANSACTION. You need privileges on the dynamic performance views to run this query.
SELECT t.used_ublk AS undo_blocks,
t.used_urec AS undo_records
FROM v$transaction t
JOIN v$session s ON s.taddr = t.addr
WHERE s.sid = SYS_CONTEXT('USERENV', 'SID');Run an update, then this query, before and after the COMMIT. After the commit the query returns no rows, because the transaction has ended. The same view is how a DBA estimates how long a long rollback still has to run: USED_UREC falls as the rollback proceeds.
Undo and savepoints
A savepoint is a marker in the sequence of undo records for your transaction. ROLLBACK TO SAVEPOINT applies undo records only back to that marker. That explains the behavior you saw earlier:
- Work done after the savepoint is undone, because its undo records are newer than the marker.
- Savepoints created later are erased, because the undo they marked has been consumed.
- The transaction stays open, and the locks taken before the savepoint are still held.
Locks taken after the savepoint may be released, which lets other sessions that were waiting on those rows proceed. This is a detail that surprises many developers, and it matters only if you rely on holding every lock until the end.
Undo and read consistency
Undo serves a second purpose that has nothing to do with rollback. When a query reads a block that has been changed by an uncommitted transaction, or committed after the query began, Oracle uses undo to rebuild an older version of the block in memory. The query then sees data as of the moment it started.
That is why a reader does not wait for a writer, as in the two-session example from the locking chapter. Session B's SELECT finds the changed row, reads the undo record that holds the old balance, and returns the committed value.
The details of isolation levels come in the next chapter. For now, remember the dependency: read consistency requires undo to still exist. If the undo for a changed row has been overwritten, a long-running query fails with:
ORA-01555: snapshot too oldUndo retention
Committed undo is kept as long as space allows, controlled by the UNDO_RETENTION parameter (in seconds). By default Oracle treats this as a target, not a guarantee. If active transactions need space, Oracle may overwrite committed undo that is older than the retention target, and a long query that needs it can get ORA-01555.
You can check the current settings:
SELECT name, value
FROM v$parameter
WHERE name IN ('undo_management', 'undo_tablespace', 'undo_retention');Two common ways to deal with ORA-01555 are to enlarge the undo tablespace and to make sure queries do not run longer than needed. A tablespace can also be created or altered with RETENTION GUARANTEE, which makes Oracle keep undo for the retention period even if that causes DML to fail with an out-of-space error. Use that option with care, because it trades query safety for write availability.
Undo and redo during a crash
Redo exists mostly for recovery. Suppose the instance crashes after you committed but before the background writer saved your data blocks. When the database restarts, Oracle runs instance recovery in two phases.
- Roll forward. Oracle replays the redo from the online redo logs, reapplying every change (committed or not) that did not reach the data files. This also rebuilds the undo blocks.
- Roll back. Oracle uses the recovered undo to reverse the changes of transactions that had not committed at the moment of the crash.
The outcome is the durability and atomicity promised by ACID. A committed transaction is replayed because its commit record is in the redo log. An uncommitted transaction is undone because no commit record exists for it.
Measuring redo and undo yourself
You can see how much redo a transaction creates by reading your session statistics before and after. This query needs access to V$MYSTAT and V$STATNAME.
SELECT n.name, m.value
FROM v$mystat m
JOIN v$statname n ON n.statistic# = m.statistic#
WHERE n.name IN ('redo size', 'undo change vector size')
ORDER BY n.name;Run it, then run an update on a few thousand rows, and run it again. The difference in redo size is the number of bytes of redo your work generated. Compare an UPDATE of a wide row with an INSERT of the same row. Inserts usually create little undo, because the undo only needs to record that the row did not exist, while updates and deletes must store the old column values.
Common misunderstandings
- "COMMIT writes my data to the data files." It does not. It writes redo. The data files catch up later.
- "A big commit takes longer than a small one." The commit record is the same size. The long part was the work before the commit.
- "Rollback is just forgetting the changes." Oracle must apply the undo, which costs time and generates redo.
- "After COMMIT the undo is gone." It is retained, subject to space and retention, so other queries can stay consistent.
- "Committing more often always helps." Frequent commits in a loop add a log write wait on every commit and make a job slower. They also increase the chance of ORA-01555, as covered in the practices chapter.
Exercise
A session updates 5 million rows and runs for 20 minutes. It then issues COMMIT, which returns almost instantly. Another session later updates 5 million rows for 20 minutes and issues ROLLBACK, which takes many minutes. Explain both observations in terms of undo and redo.
Show answer
At COMMIT, Oracle only has to write a commit record and flush the redo log buffer through LGWR. The data blocks do not need to be written, and the redo for the earlier changes was already being flushed in the background, so the commit is short and does not depend on the number of rows. ROLLBACK has to read every undo record for the 5 million changes and apply each one to a data block, newest first, and each application also generates redo. The work is proportional to the amount of change, so it takes a time similar to the original update.
Exercise
A report query that runs for two hours fails with ORA-01555, although no one changed the report tables for the last hour. Which feature does the query depend on, what probably happened, and name two ways to reduce the risk.
Show answer
The query depends on read consistency, which rebuilds old block versions from undo. Other sessions changed other data and committed, and Oracle reused committed undo space that the query still needed, because UNDORETENTION is a target and not a guarantee (the undo needed by this query included changes made earlier in the two hours). To reduce the risk, enlarge the undo tablespace or raise UNDORETENTION, and shorten the query or run it at a quieter time. RETENTION GUARANTEE on the undo tablespace is another option, with the cost that DML can fail when undo space runs out.