$ show tokio-rs/mini-redis
mini-redis is an incomplete, idiomatic implementation of a Redis client and server built with Tokio, serving as a teaching resource for asynchronous Rust patterns. The server supports key-value operations (GET, SET) with optional TTL, pub/sub (PUBLISH, SUBSCRIBE, UNSUBSCRIBE), and PING. It demonstrates graceful shutdown, connection limiting via a semaphore, and key expiration using a background task. The client library provides async (Client), blocking (BlockingClient), and buffered (BufferedClient) clients, with a Subscriber type for pub/sub. The codebase is well-structured, extensively commented, and showcases patterns such as frame-level protocol parsing, shared state with std::sync::Mutex, message-passing for multiplexing, and broadcast channels for shutdown signals. It is not intended for production use but is a high-quality reference for learning Tokio and async Rust.
The LLM identified 3 files worth highlighting for reuse:
Provides a type representing a Redis protocol frame (Frame enum) with utilities for parsing frames from a byte array. Implements a two-step parse: a fast `check` to determine if a complete frame is available, and `parse` to construct the frame. Handles edge cases like incomplete data, invalid negative bulk lengths, and various frame types. This module is self-contained (depends only on bytes, std) and could be extracted for any Redis protocol implementation.
A reusable wrapper around a broadcast::Receiver that tracks whether a shutdown signal has been received. Provides `is_shutdown` and `recv` methods. Demonstrates a clean pattern for propagating shutdown signals across concurrent tasks. The module has no dependencies beyond tokio::sync::broadcast and is easily extractable for any async application needing coordinated shutdown.
Implements the in-memory key-value store and pub/sub channel state. Uses `std::sync::Mutex` (not Tokio mutex) because critical sections are small and do not involve async operations. Manages key expiration via a `BTreeSet` sorted by expiration time and a background task that uses `tokio::sync::Notify` to wake up on new expirations or shutdown. The design demonstrates safe use of blocking mutexes in async contexts and an efficient expiration mechanism. While tied to Redis semantics, the pattern of a shared state with a background purge task is broadly reusable.