A Minimal “Redis-like” Server in Modern C++ [#48-1]

A Minimal “Redis-like” Server in Modern C++ [#48-1]

이 글의 핵심

Event-driven TCP server + line protocol + unordered_map—learning path toward real Redis internals.

Introduction: build a tiny Redis-shaped server

Redis uses a single-threaded event loop and in-memory KV operations. This tutorial implements a minimal line-oriented protocol with Boost.Asio so you see end-to-end: accept → session → parse → std::unordered_map.

Prerequisites: Asio intro (#29-1), network guide #1.


Table of contents

  1. Architecture
  2. Server, acceptor, session
  3. Protocol
  4. Storage
  5. Complete example
  6. Common errors
  7. Performance tips
  8. Production patterns
  9. Run & extend

1. Architecture

flowchart TB
    subgraph io["Single-thread io_context"]
        A[Acceptor :6379]
        S1[Session]
        S2[Session]
    end
    M[unordered_map key→value]
    A --> S1 & S2
    S1 & S2 --> M

One thread runs io_context::run(), async_accept spawns sessions, each uses async_read_until('\n') and async_write responses.


2. Server & session

enable_shared_from_this keeps Session alive across async operations. On each line, parse GET/SET/DEL/QUIT.


3. Protocol (simplified)

One text line per command: GET key, SET key value (use getline for value tail), DEL key. This toy parser is not full RESP—refer to Redis RESP specs for binary-safe framing and bulk strings.


4. Storage

static std::unordered_map<std::string,std::string> is fine single-threaded. Add mutex/strand if you add worker threads.


5. Complete example

The companion redis_clone_minimal.cpp listing compiles with -lboost_system -pthread; you can probe it via telnet or redis-cli (text mode limitations apply).


6. Common errors

Port in use → change port or SO_REUSEADDR; bad_weak_ptr → construct Session via make_shared; multithreaded map access → data race—serialize with strand/mutex.


7. Performance tips

TCP_NODELAY, buffer sizing, reserve on the map, reuse response buffers.


8. Production patterns

Signal handling for graceful shutdown, connection limits, TTL structs, optional snapshot/load, metrics INFO command.


9. Run & extend

Multithread io_context with care; implement RESP; add lists/sets for learning data structures.


Keywords

Redis clone, Boost.Asio, in-memory KV, event loop, C++ networking

Next: HTTP framework (#48-2)
Previous: Rust vs C++ memory (#47-3)