Skip to content

learnwithparam/build-your-own-redis-ruby

Repository files navigation

Build your own Redis in Ruby

Sibling to the Python, Go, Node.js, and Rust workshops. Same architectural progression, idiomatic Ruby with socket, Thread, Mutex, Queue, and ConditionVariable.

The build

# Step Ruby idiom
01 TCP echo TCPServer + Thread per connection
02 RESP parser byteslice + tagged-array sum type
03 GET / SET Hash + Mutex.synchronize + case/when
04 Expiry sidecar Hash + Time.now.to_f deadlines
05 AOF persistence File.open('ab') + log_to_aof: false
06 RDB snapshots JSON.dump + File.rename atomic
07 Pub/Sub per-subscriber Queue + write-pump Thread
08 Replication master/replica via ARGV + SYNC
09 Graceful shutdown Signal.trap + ConditionVariable + RDB on exit
10 Capstone benchmark sequential RESP load + percentile report

Each step folder ships with server.rb, README.md, GUIDE.md, EXERCISES.md.

Getting started

Requires Ruby 3.0+.

git clone https://github.com/learnwithparam/build-your-own-redis-ruby.git
cd build-your-own-redis-ruby
make 01-tcp-echo

In another terminal:

nc localhost 6380
> hello
< hello

Run any step

make 01-tcp-echo
make 02-resp-parser
make 03-get-set
make 04-expiry
make 05-aof-persistence
make 06-rdb-snapshots
make 07-pubsub
make 08-replication             # master on 6380; replica with: ruby 08-replication/server.rb replica 6381 127.0.0.1 6380
make 09-graceful-shutdown
make 10-capstone                # benchmark vs real Redis on 6379
make test                       # ruby -c every server file + doc check

Why Ruby

  • Threads + GIL: enough for an IO-bound server; honest about its CPU ceiling
  • Mutex.synchronize: block-scoped lock acquisition, exception-safe by design
  • Queue and ConditionVariable: lock-free coordination primitives shipped in stdlib
  • Signal.trap: clean signal handling without sigaction(2) ceremony
  • Fiber.schedule (Ruby 3+): bonus path to a single-threaded event loop in exercise 1.4

Sibling workshops

Concept Python Go Node Rust Ruby
Concurrency Threads or selectors Goroutines Event loop tokio tasks Threads (+ Fiber 3+)
Shared state dict + lock sync.RWMutex Map (no lock) Arc<Mutex> Hash + Mutex
Pub/Sub fan-out Connection list Buffered chan Set broadcast channel Queue per subscriber
Sum type duck typing interface{} discriminated objects enum tagged array

License

MIT.

About

Build your own Redis in Ruby — 10 incremental steps, sibling of Python/Go/Node/Rust workshops

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors