🎓 A1Learner
🔍
0 of 47 lessons completed

Write-Through and Write-Back

Write strategies decide when a new value reaches the database. Write-through sends each write to the database at once, and write-back sends saved writes later.

Write-through writes at once

3 values are written. The database write count rises with every single write.

cache = {}
db = {}
db_writes = 0

def write_through(key, value):
    global db_writes
    cache[key] = value
    db[key] = value
    db_writes += 1
    print("database writes so far:", db_writes)

write_through("a", 1)
write_through("b", 2)
write_through("c", 3)
print("values in database:", len(db))

Write-back waits for a flush

The same 3 writes land in the cache only. The database stays untouched until the flush, the moment saved writes are sent on.

cache = {}
db = {}
pending = []

def write_back(key, value):
    cache[key] = value
    pending.append(key)
    print("database writes so far:", len(db))

def flush():
    for key in pending:
        db[key] = cache[key]
    pending.clear()
    print("after flush, database writes:", len(db))

write_back("a", 1)
write_back("b", 2)
write_back("c", 3)
flush()

What a crash keeps

A crash here means the cache is wiped before any flush. Only values already in the database survive.

def run(write):
    cache = {}
    db = {}
    pending = []
    for key, value in [("a", 1), ("b", 2)]:
        write(cache, db, pending, key, value)
    cache.clear()
    return len(db)

def write_through(cache, db, pending, key, value):
    cache[key] = value
    db[key] = value

def write_back(cache, db, pending, key, value):
    cache[key] = value
    pending.append(key)

print("write-through values kept:", run(write_through))
print("write-back values kept:", run(write_back))

Example

values = [("a", 1), ("b", 2), ("c", 3), ("d", 4)]

cache = {}
db = {}
for key, value in values:
    cache[key] = value
    db[key] = value
print("write-through database writes:", len(db))

cache = {}
db = {}
pending = []
for key, value in values:
    cache[key] = value
    pending.append(key)
print("write-back database writes before flush:", len(db))
for key in pending:
    db[key] = cache[key]
print("write-back database writes after flush:", len(db))

Key points

  • Write-through: a write goes to the cache and to the database in the same step.
  • Write-back: a write goes to the cache now and reaches the database later, when a flush sends the saved writes on.
  • Use write-through when the database must hold every value straight away.
  • Use write-back to group many writes into fewer trips to the database.

In this example, 4 values are written both ways. Write-through reaches 4 database writes at once, while write-back sits at 0 until its flush also reaches 4.

Note

a crash before a flush loses any write that exists only in the cache.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which strategy can lose new values if the server crashes before a flush?