Skip to main content

Chapter 4: Persistence

A database that loses all data on restart isn’t very useful! In this chapter, we’ll implement both persistence strategies Redis uses: RDB snapshots and AOF (Append-Only File) logging. This chapter teaches one of the most fundamental trade-offs in all of systems engineering: durability vs. performance. Every write to disk costs time. The question is when you pay that cost and how much data you are willing to lose if the power goes out. RDB and AOF represent two different answers to this question, and understanding both will inform your thinking about databases, message queues, and any system that claims to “persist” data.
Prerequisites: Chapter 3: Data Structures
Further Reading: Database Engineering: Storage Engines
Time: 3-4 hours
Outcome: Data survives server restarts

Persistence Strategies Overview


Part 1: RDB Snapshots

RDB creates a point-in-time snapshot of all data in a binary format.

RDB File Format

RDB Encoder

internal/persistence/rdb.go

RDB Reader

internal/persistence/rdb_reader.go

Part 2: Background Saves (BGSAVE)

Redis forks to create snapshots without blocking the main process.
internal/persistence/bgsave.go

Part 3: Append-Only File (AOF)

AOF logs every write command for maximum durability.

AOF Writer

internal/persistence/aof.go

AOF Loader

internal/persistence/aof_loader.go

Part 4: AOF Rewriting

Over time, AOF files grow. Rewriting compacts them:
internal/persistence/aof_rewrite.go

Part 5: Integrating Persistence

internal/server/server.go

Exercises

Persist key expiration times:
Add the BGREWRITEAOF command:
Add LZF compression to RDB:

Key Takeaways

RDB Snapshots

Point-in-time backups, compact but may lose recent data

AOF Logging

Every write logged, durable but larger files

Checksums

CRC64 ensures data integrity

AOF Rewriting

Compact AOF by rebuilding from current state

What’s Next?

In Chapter 5: Pub/Sub, we’ll implement:
  • Publish/Subscribe messaging
  • Pattern subscriptions
  • Real-time event streaming

Next: Pub/Sub

Implement real-time messaging