Key-Value Store Database
Lets look at Bigger picture on what we are building
component1: Storage Engine — Append-only Log
component2: Indexing — Persistent Indexer using Checkpoints
component3- Write Ahead Log
component4- Compaction — deleting garbage data
component 5- Concurrency control
let start with Storage Engine
In our storage engine we have three main functions put,get,delete
-we will store the data in a text file in the format
PUT,name,Alice
PUT,age,25
PUT,name,Bob
DELETE,age
PUT,city,NYC
-we will skip if we found delete word
-with the get function we will get the latest values
Component 2 Indexing
-For this we are building Persistent Indexing
-why do we need indexing it will help to fetch data faster -After every five operations we will create a checkpoint so when we cold start the database the startup time will be fast
Component 3 — write Ahead Log
-In simple terms we will write to the log before updating memory
Component 4 — Compaction
-As we only want the latest updated values the old values become garbage -So we will run a program after 30 operations to delete the old file and create a new file with latest values
-By we can save lot of time during startup and size of the file
Component 5 — Concurrency Control
-let us look at a scenario where a user is read a value an another user is updating the value at same time which will lead to data mismatch. -So will put a lock when we are updating data so other programs have to wait until it is completed
Get Dolapavan’s stories in your inbox
Join Medium for free to get updates from this writer.
-we will use write locks for put and delete and read locks for get
Actual implementation
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class SimpleStorage {
// required fields
private String filename;
private PrintWriter writer;
private int currentLineNumber = 0;
private int checkpointLineNumber = 0;
private int operationsSinceCheckpoint = 0;
private static final int CHECKPOINT_THRESHOLD = 5;
private HashMap<String, String> index;
private static final int COMPACTION_THRESHOLD = 30;
private int totalOperations = 0;
private ReadWriteLock lock;
private Lock readLock;
private Lock writeLock;
//constructor
public SimpleStorage(String filename) throws IOException {
this.filename = filename;
this.writer = new PrintWriter(new FileWriter(filename, true));
this.index = new HashMap<>();
this.lock = new ReentrantReadWriteLock();
this.readLock = lock.readLock();
this.writeLock = lock.writeLock();
loadCheckpoint();
replayLog();
}
// our put method with cconcurrency implementation
public void put(String key, String value) {
writeLock.lock();
try {
writer.println("PUT," + key + "," + value);
writer.flush();
index.put(key, value);
operationsSinceCheckpoint++;
totalOperations++;
if (operationsSinceCheckpoint == CHECKPOINT_THRESHOLD) {
checkpoint();
operationsSinceCheckpoint = 0;
}
} finally {
writeLock.unlock();
}
}
public void delete(String key) {
writeLock.lock();
try {
writer.println("DELETE," + key);
writer.flush();
index.remove(key);
operationsSinceCheckpoint++;
totalOperations++;
if (operationsSinceCheckpoint == CHECKPOINT_THRESHOLD) {
checkpoint();
operationsSinceCheckpoint = 0;
}
} finally {
writeLock.unlock();
}
}
// our checkpoint method after 5 operations
private void checkpoint() {
try {
if (totalOperations % COMPACTION_THRESHOLD == 0) {
// calling our compact method if it is more than 30 opertaions
compact();
totalOperations = 0;
} else {
countLines();
}
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("checkpoint.dat"));
out.writeInt(currentLineNumber);
out.writeObject(index);
out.close();
checkpointLineNumber = currentLineNumber;
System.out.println("Checkpoint created at line " + currentLineNumber);
} catch (IOException e) {
System.err.println("Checkpoint failed: " + e.getMessage());
}
}
private void countLines() throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(filename));
int count = 0;
while (reader.readLine() != null) {
count++;
}
reader.close();
currentLineNumber = count;
}
public void close() throws IOException {
writeLock.lock();
try {
checkpoint();
writer.close();
} finally {
writeLock.unlock();
}
}
public String get(String key) throws IOException {
readLock.lock();
try {
return index.get(key);
} finally {
readLock.unlock();
}
}
// load checkpoint loads our file into memory on startup
private void loadCheckpoint() {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream("checkpoint.dat"));
checkpointLineNumber = in.readInt();
index = (HashMap<String, String>) in.readObject();
in.close();
System.out.println("Loaded checkpoint from line " + checkpointLineNumber);
} catch (FileNotFoundException e) {
System.out.println("No checkpoint found, starting fresh");
} catch (IOException | ClassNotFoundException e) {
System.err.println("Failed to load checkpoint: " + e.getMessage());
}
}
// fill our in memory indexer hashmap on start
private void replayLog() throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line;
int lineNumber = 0;
while ((line = reader.readLine()) != null) {
lineNumber++;
if (lineNumber <= checkpointLineNumber) {
continue;
}
String[] values = line.split(",");
if (values[0].equals("DELETE")) {
index.remove(values[1]);
} else
index.put(values[1], values[2]);
}
currentLineNumber = lineNumber;
System.out.println("currentline after replay: " + currentLineNumber);
reader.close();
}
private void compact() throws IOException {
System.out.println("Starting compaction...");
writer.close();
File tempFile = new File(filename + ".tmp");
PrintWriter tempWriter = new PrintWriter(new FileWriter(tempFile));
currentLineNumber = 0;
for (Map.Entry<String, String> entry : index.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
tempWriter.println("PUT," + key + "," + value);
currentLineNumber++;
}
tempWriter.flush();
tempWriter.close();
File oldFile = new File(filename);
oldFile.delete();
File newfile = new File(filename);
tempFile.renameTo(newfile);
writer = new PrintWriter(new FileWriter(filename, true));
checkpointLineNumber = currentLineNumber;
System.out.println("Compaction complete. Lines: " + currentLineNumber);
}What we Built So Far Component 1: Storage Engine
- Append-only log (never lose data)
- Durable writes with flush
- Handles updates and deletes via tombstones
Component 2: Indexing
- In-memory HashMap for O(1) lookups
- Persistent checkpoints for fast startup
- Smart replay from checkpoint
Component 3: Write-Ahead Log (WAL)
- Always write to log before updating memory
- Crash recovery by replaying log
- Durability guarantees
Component 4: Compaction
- Removes garbage (old versions, deleted keys)
- Reclaims disk space
- Triggered automatically every N operations
Component 5: Concurrency Control
- ReadWriteLock for thread safety
- Multiple readers can work simultaneously
- Writers get exclusive access
- No data corruption, no race conditions
What You’ve Learned
Why databases are slow or fast
- Disk I/O is the bottleneck
- Indexing makes reads fast
- Compaction trades CPU for disk space
- Locks serialize access (safety vs speed)
How real databases work
- PostgreSQL, MySQL, MongoDB all use these concepts
- LSM-Trees (LevelDB, RocksDB) work exactly like this
- Redis uses similar in-memory indexes
Computer Science fundamentals
- File I/O and buffering
- Data structures (HashMap)
- Concurrency (locks, race conditions)
- Trade-offs (performance vs durability)




