LogoMasst Docs

Write-Behind

Understanding the write-behind (write-back) caching pattern.

What is Write-Behind?

Write-Behind (also called Write-Back) is a caching pattern where writes are first stored in the cache and then asynchronously persisted to the database.


How It Works

Application                Cache                Database
     │                       │                     │
     │─── Write(key, data) ─►│                     │
     │                       │                     │
     │◄── OK (immediate) ────│                     │
     │                       │                     │
     │                       │    (async later)    │
     │                       │─── Write ──────────►│
     │                       │◄── OK ─────────────│

Key Characteristics

AspectDescription
Write speedVery fast (memory only)
ConsistencyEventually consistent
BatchingCan batch multiple writes
RiskData loss if cache fails before DB write

Advantages

BenefitDescription
Lowest write latencyReturns immediately after cache write
Write coalescingMultiple updates to same key = one DB write
Reduced DB loadBatched writes, fewer DB operations
Better throughputNot blocked by DB latency

Disadvantages

DrawbackDescription
Data loss riskCache failure before DB sync
ComplexityNeed queue/retry logic
Eventual consistencyDB may lag behind cache
Recovery complexityNeed to handle failed writes

Implementation Pattern

class WriteBackCache:
    def __init__(self):
        self.cache = {}
        self.dirty_keys = set()

    def write(self, key, value):
        self.cache[key] = value
        self.dirty_keys.add(key)
        return True  # Return immediately

    # Background job
    def flush_to_db(self):
        for key in self.dirty_keys:
            db.write(key, self.cache[key])
        self.dirty_keys.clear()

Use Cases

Good for:

  • Write-heavy workloads
  • Data that changes frequently (counters, metrics)
  • Acceptable data loss risk
  • Latency-sensitive applications

Not ideal for:

  • Critical data (financial transactions)
  • Strong consistency requirements
  • Audit/compliance needs

Comparison

PatternWrite LatencyData SafetyConsistency
Write-ThroughHighHighStrong
Write-BehindLowLowerEventual
Cache-AsideMediumHighEventual

Interview Tips

  • Explain async write mechanism
  • Discuss data loss risk and mitigation
  • Mention write coalescing benefit
  • Compare with write-through pattern
  • Give use cases: counters, analytics, logs