Skip to content
C project #24Advanced

Persistent Key-Value Store

A tiny Redis-like database: a resizable hash table in memory, an append-only log on disk, crash recovery by replay and log compaction.

Estimated time
~12 hours to build
Files
7 files · 502 lines
Technologies
C11, Text file I/O

Introduction

Databases are built on two ideas you can implement in C: an in-memory index for fast lookups and a durable log on disk. This project combines them into a working key-value database with a command interface.

Problem statement

Implement SET, GET, DEL, EXISTS, INCR, KEYS [prefix], COUNT, STATS, COMPACT and RESTART. Every change must be appended to a log before it is applied, so that restarting the program replays the log and recovers all data. COMPACT rewrites the log with only the current keys. The hash table must grow automatically.

Objectives

  • Implement a hash table with chaining and rehashing
  • Design write-ahead logging and recovery
  • Implement log compaction safely
  • Parse a command protocol

Features

  • FNV-1a hashing with automatic resizing at load factor 0.75
  • Append-only log with replay on start-up
  • Compaction via temporary file and rename
  • Prefix key listing (sorted)
  • INCR with type checking
  • Statistics: buckets, load factor, chain length

Concepts demonstrated

  • Hashing
  • Write-ahead logging
  • Crash recovery
  • Compaction
  • Amortised resizing

System architecture

kvstore.c keeps entries in buckets[hash % nbuckets] chains. kv_set/kv_del first append a line to data.log, then change memory (log-first gives durability). kv_open replays the log. kv_compact writes all live keys to data.log.tmp and renames it over the log. main.c parses commands case-insensitively.

TextArchitecture diagram
SET k v ─> append "SET k v" to data.log ─> update hash table
start-up ─> replay data.log ─> hash table rebuilt
COMPACT ─> write live keys to data.log.tmp ─> rename

Folder structure

TextProject tree
key-value-store/
├── README.md
├── Makefile
├── src/kvstore.c
├── src/kvstore.h
├── src/main.c
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

Makefile

20 lines
MakefileMakefile
# Generated for KENHOLT Skills. Usage: make | make test | make clean
CC = gcc
CFLAGS = -std=c11 -Wall -Wextra -O2
SRC := $(wildcard src/*.c)
HDR := $(wildcard src/*.h)
ARGS := $(shell cat tests/args.txt 2>/dev/null)
INPUT := $(wildcard tests/sample-input.txt)
app: $(SRC) $(HDR)
$(CC) $(CFLAGS) -Isrc $(SRC) -o app -lm
test: app
./app $(ARGS) $(if $(INPUT),< $(INPUT),) > actual.txt
diff actual.txt tests/expected-output.txt && echo "Test passed: output matches tests/expected-output.txt"
clean:
rm -f app app.exe actual.txt
.PHONY: test clean

What each file does

src/kvstore.h
Store and entry types and the API, with the design explained.
src/kvstore.c
Hashing, rehashing, in-memory set/delete, logging, replay, compaction and sorted key listing.
src/main.c
The command interpreter, INCR, STATS and RESTART.
Makefile
Build automation: make builds ./app, make test runs the sample session and compares it with the expected output, make clean removes build files.

How to run it

Build

Terminal
gcc -std=c11 -Wall -Wextra -Isrc src/*.c -o app -lm
# or simply: make

Run

Terminal
./app # Linux / macOS
.\app.exe # Windows

Test against the expected output

Terminal
./app < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt # no output means they match
# Windows PowerShell:
# Get-Content tests\sample-input.txt | .\app.exe > actual.txt
# Compare-Object (Get-Content actual.txt) (Get-Content tests\expected-output.txt)

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
kvdb ready: 0 key(s) recovered from data.log
kvdb> SET user:1 Asha Rao
OK
kvdb> SET user:2 Vikram Shah
OK
kvdb> SET course:c C Programming
OK
kvdb> GET user:1
"Asha Rao"
kvdb> GET user:9
(nil)
kvdb> SET user:1 Asha R.
OK
kvdb> INCR visits
(integer) 1
kvdb> INCR visits
(integer) 2
kvdb> INCR visits
(integer) 3
kvdb> EXISTS visits
(integer) 1
kvdb> KEYS user:
1) user:1
2) user:2
kvdb> DEL user:2
(integer) 1
kvdb> DEL user:2
(integer) 0
kvdb> COUNT
(integer) 3
kvdb> STATS
keys 3 | buckets 8 (2 used) | load factor 0.38 | longest chain 2 | log records 8
kvdb> COMPACT
OK (log 8 -> 3 records)
kvdb> RESTART
restarted: 3 key(s) recovered
kvdb> GET user:1
"Asha R."
kvdb> KEYS
1) course:c
2) user:1
3) visits
kvdb> quit
bye
Input
SET user:1 Asha Rao
SET user:2 Vikram Shah
SET course:c C Programming
GET user:1
GET user:9
SET user:1 Asha R.
INCR visits
INCR visits
INCR visits
EXISTS visits
KEYS user:
DEL user:2
DEL user:2
COUNT
STATS
COMPACT
RESTART
GET user:1
KEYS
quit

Testing

  • Diff with tests/expected-output.txt (RESTART proves recovery from the log).
  • Kill the program (Ctrl+C) after some SETs, start it again and GET the keys.
  • Insert 10,000 keys in a script and check STATS shows the table has grown.

Common errors

Values with spaces are truncated

The value is everything after the key (line + used), not a single %s word.

Log keeps growing

Run COMPACT; every SET of an existing key adds a record until compaction.

Possible improvements

  • Expiry times (TTL) for keys
  • A binary log format with checksums
  • Snapshotting plus log, like Redis RDB + AOF

Additional challenges

  1. 1Serve commands over a TCP socket so multiple clients can connect.
  2. 2Add transactions: MULTI … EXEC applied atomically.
  3. 3Measure SET/GET throughput for one million keys.

Built and tested it yourself? Mark it to update your dashboard.