RDB: JSON dump + atomic File.rename

Ruby has fork but using it inside a Threaded server is risky. We do a shallow $store.dup under the lock, serialise outside, atomic File.rename.

06-rdb-snapshots/server.rb
ruby
def snapshot_atomic
  snap = $mu.synchronize { $store.dup }
  tmp = "#{RDB_PATH}.tmp"
  File.binwrite(tmp, JSON.dump(snap))
  File.rename(tmp, RDB_PATH)
  snap.size
end

Lock briefly to dup, then release. The dup is a fresh map nobody else sees.

06-rdb-snapshots/server.rb
ruby
when 'BGSAVE', 'SAVE'
  Thread.new { snapshot_atomic }
  encode_simple('Background saving started')

BGSAVE runs snapshot_atomic in a Thread so the client gets +OK immediately.

Dup-under-lock vs fork+COW

Ruby pays memory briefly at snapshot time. C forks and pays only for pages that diverge during save.

Quiz: Quiz

Loading practice…