Write Through
Write through
The application will write to both database and cache
Loading...
Pros:
- Consistency, cache always up to date
- If the system crash, there is always cache that will have the data
Cons - The key that we write we are not guarantee that it's read heavy therefore we doubled up the storage.
We can improve this cons by introducing invalidation
sequenceDiagram
participant App as Application
participant Cache as Cache
participant DB as Database (Master)
Note over App, DB: Write-Through Process
App->>Cache: 1. Write Data
App->>DB: 2. Write Data
DB-->>App: 3. Confirm Write
Cache-->>App: 4. Confirm Write
App-->>User: 5. Success (Both updated)
Write through with invalidation
Loading...
Basically, we leave the responsibility of updating the cache to read strategy. When reading, if the cache is missing, the read strategy will automatically update the cache.
Pros:
- All the pros from above
- Improve writing speed (delete is faster than write new value to cache)
Cons: - Database replica lag might happen where:
- scenario:
- Data is write to the master database. Takes
Xtime to sync to replica - Data is deleted from cache
- Other instance try to read the same data, it query from read replica to update the cache, but it's lagged
- Data is write to the master database. Takes
- In this case, consider: Database Replica lag solution
- scenario:
sequenceDiagram
participant App as Application
participant Cache as Cache
participant DB as Database (Master)
Note over App, DB: Write Phase
App->>DB: 1. Update/Write Data
App->>Cache: 2. Invalidate (Delete) entry
Cache-->>App: 3. Acknowledge Deletion
DB-->>App: 4. Confirm Success
Note over App, DB: Subsequent Read Phase
App->>Cache: 5. Read Request
Cache-->>App: 6. Cache Miss (Data deleted)
App->>DB: 7. Fetch fresh data
DB-->>App: 8. Return fresh data
App->>Cache: 9. Populate Cache with fresh data