Log Based Recovery: Definition, How It Works, and Examples
database management systems (DBMS) that uses a log file to record all changes made to the database. In case of a failure, the system uses this log to restore the database to a consistent state by redoing or undoing transactions.How It Works
Imagine you are writing a diary where you note down every change you make to your room, like moving furniture or adding decorations. If something goes wrong, you can look back at your diary to undo or redo those changes and restore your room to how it was.
In log based recovery, the database keeps a similar diary called a log file. Every time the database changes, it records the details in this log before applying the change. If the system crashes or loses power, the database uses the log to replay (redo) changes that were committed but not saved, or undo changes from incomplete transactions. This ensures the database stays accurate and reliable.
Example
This simple Python example simulates a log based recovery by recording operations and then restoring the final state after a failure.
class SimpleDB: def __init__(self): self.data = {} self.log = [] def update(self, key, value): # Log the operation before applying self.log.append(('update', key, value)) self.data[key] = value def recover(self): # Clear current data and replay log self.data = {} for entry in self.log: op, key, value = entry if op == 'update': self.data[key] = value # Usage mydb = SimpleDB() mydb.update('x', 10) mydb.update('y', 20) # Simulate failure and recovery mydb.recover() print(mydb.data)
When to Use
Log based recovery is essential in any system where data integrity is critical, such as banking, online shopping, or airline booking systems. It helps recover from unexpected crashes, power failures, or software errors without losing committed data.
Use log based recovery when you need to ensure that all completed transactions are saved and incomplete ones are rolled back, maintaining the database's consistency and reliability.
Key Points
- Logs record every change before it happens.
- Recovery uses logs to redo or undo transactions.
- Ensures database consistency after failures.
- Critical for systems requiring high reliability.