Skip to content
CurriculumLesson 34 ยท Files
Advanced~14 min

File Indexing & Updating

An index is only useful if it stays correct. Updates must change the data and every index that points to it, and a crash in the middle must not leave the file inconsistent.

In plain English

An index is a map. When a street changes, every map that shows it must be updated.

By the end you will be able to

  • Explain index maintenance on insert, delete, and update.
  • Compare in-place and out-of-place updates.
  • Explain write-ahead logging.
  • Know how recovery uses the log.
01

Maintaining indexes

Every insert adds an index entry; every delete removes one; every key update removes the old entry and adds a new one. A dense index may need more work than a sparse index. If an index is sorted, inserting a key may require splitting a block. The file system must keep the data and index consistent even if a crash occurs between the two writes.

02

In-place versus out-of-place

An in-place update overwrites the old record. If the system crashes midway, the record may be half written. An out-of-place update writes a new version to a free block, then atomically switches the pointer. The old version remains available until the switch is committed, which makes recovery simpler.

lesson-34.osOS
in-place:
write(record_block, new_value)   /* crash here = torn record */

out-of-place:
new_block = write(new_value)
commit_pointer(record -> new_block)
free(old_block)
03

Write-ahead logging

Before changing a data block, write a log record describing the change. The log is forced to stable storage before the data block is written. After a crash, recovery scans the log: committed transactions are redone, incomplete ones are undone. This is the foundation of crash-safe file systems and databases.

lesson-34.osOS
log.append({ op: "update", key: 42, old: A, new: B });
log.flush();
write_data_block(42, B);
log.commit();

Key takeaways

  • Every index must be updated when the data changes.
  • In-place updates risk torn records on a crash.
  • Out-of-place updates switch a pointer atomically.
  • Write-ahead logging records intent before data changes.
  • Recovery redoes committed work and undoes incomplete work.

Common pitfalls

  • Updating data without updating its indexes.
  • Assuming a single block write is atomic.
  • Forgetting to flush the log before writing data.

Kernel notes

  • List the index work for an insert and a delete.
  • Explain the torn-write problem.
  • Trace redo and undo during recovery.

Quick check

0 / 2 answered

1. What is the purpose of a write-ahead log?

2. What is an out-of-place update?