Persistence
In this stage, you’ll add persistence to your key-value store. Data should survive clean shutdowns and be restored when the server restarts.
Graceful Shutdown
Section titled “Graceful Shutdown”When your server receives a termination signal (SIGTERM or SIGINT), it should:
- Wait for in-flight requests to complete (within 5 seconds)
- Save all key-value pairs to disk
- Exit with status code
0
Startup Recovery
Section titled “Startup Recovery”When your server starts, it should:
- Check the
DATA_DIRenvironment variable for the data directory path - Load any previously saved key-value pairs
- Continue serving requests with the restored data
If no previous data exists, start with an empty store.
Storage
Section titled “Storage”Save your in-memory state to disk during shutdown and restore it on startup. Create your data files in the directory given by the DATA_DIR environment variable. The serialization format and file naming are up to you - JSON, binary (Protocol Buffers, MessagePack, BSON, gob, pickle), plain text, whatever.
This approach survives clean shutdowns but not crashes. If the process dies unexpectedly, you’ll lose any data that wasn’t saved. That’s fine for this stage - you’ll add crash recovery in the next stage.
Testing
Section titled “Testing”The test harness mounts a persistent volume at /app/data and sets the DATA_DIR environment variable to /app/data.
You can test your implementation using the clstr command:
$ clstr testTesting persistence: Data Survives SIGTERM
✓ Data Survives a Graceful Restart✓ All Data Survives Repeated Graceful Restarts✓ Rapid Sequential Writes Survive a Graceful Restart✓ Rapid Concurrent Writes Survive a Graceful Restart✓ CLEAR Survives a Graceful Restart
PASSED ✓
Run 'clstr next' to advance to the next stage.The tests will:
- Store data in your server
- Send SIGTERM to trigger graceful shutdown
- Restart your server
- Verify all data is still present
Debugging
Section titled “Debugging”Your server’s output (stdout/stderr) is captured during testing and viewable with clstr logs. The STOPPED and STARTED markers show exactly when the server was restarted:
$ clstr logs n1
================ STARTED ================
Server listening on 0.0.0.0:8080PUT /kv/kenya:capital accepted, value=NairobiPUT /kv/germany:capital accepted, value=BerlinFlushing 2 keys to /app/data/store.json
================ STOPPED ================
================ STARTED ================
Server listening on 0.0.0.0:8080Loaded 2 keys from /app/data/store.jsonGET /kv/kenya:capital returning 200GET /kv/germany:capital returning 200Resources
Section titled “Resources”- Designing Data-Intensive Applications Chapter 4: Encoding and Evolution by Martin Kleppmann