Khi process A gọi fork(), OS tạo process B là bản copy của A. Nếu copy toàn bộ memory ngay lập tức thì tốn kém và lãng phí (nhất là khi child chỉ exec một program khác sau fork). Copy-on-Write (CoW): sau fork, parent và child share cùng physical memory pages, đều chỉ có read-only mapping. Khi một bên (thường là child) write vào page → hardware fault → OS copy chỉ page đó ra một bản riêng → write vào bản copy. Pages không bị write thì không bao giờ copy — save memory và time.
Tại sao quan trọng với Redis RDB snapshot: khi Redis fork một child process để ghi RDB snapshot ra disk, child và parent share toàn bộ memory via CoW. Child đọc data để serialize (không write). Parent tiếp tục serve requests và write. Mỗi page parent write → copy của page đó. Nếu Redis đang write nhiều trong khi snapshot → nhiều page bị copy → memory tăng đột biến (used_memory + used_memory_rss diverge).
Monitoring: rdb_last_bgsave_time_sec, latest_fork_usec, Redis INFO stats. Tip: Redis fork nhanh nhất khi không có memory fragmentation và THP disabled.
When process A calls fork(), the OS creates process B as a copy of A. Copying all memory immediately would be expensive and wasteful (especially if the child only execs a different program right after forking). Copy-on-Write (CoW): after forking, parent and child share the same physical memory pages, both with read-only mappings. When either side (usually the child) writes to a page → a hardware fault is triggered → the OS copies only that page → the write goes to the copy. Pages that are never written are never copied — saving both memory and time.
Why it matters for Redis RDB snapshots: when Redis forks a child process to write an RDB snapshot to disk, the child and parent share all memory via CoW. The child reads data to serialize (no writes). The parent continues serving requests and writing. Every page the parent writes → that page is copied. If Redis receives heavy writes during a snapshot → many pages are copied → memory spikes (used_memory and used_memory_rss diverge).
Monitoring: rdb_last_bgsave_time_sec, latest_fork_usec, Redis INFO stats. Tip: Redis forks fastest when there is no memory fragmentation and Transparent Huge Pages (THP) is disabled.