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
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.
Folder structure
Complete source code
Makefile
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:
makebuilds./app,make testruns the sample session and compares it with the expected output,make cleanremoves build files.
How to run it
Build
Run
Test against the expected output
Expected output
Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.
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
- 1Serve commands over a TCP socket so multiple clients can connect.
- 2Add transactions: MULTI … EXEC applied atomically.
- 3Measure SET/GET throughput for one million keys.
Built and tested it yourself? Mark it to update your dashboard.