Understanding Redis Single-Threaded Architecture and Core Commands
Fundamantal Redis Commands
Redis provides essential commands for key-value operations. The most basic are:
SET key value: Assigns a value to a key.GET key: Retrieves the value of a key. Returnsnilif the key doesn’t exist.
To handle binary-safe strings correctly in the CLI, use redis-cli --raw.
Global Commands
KEYS pattern: Matches keys using glob-style patterns (e.g.,?,*,[abc]). AvoidKEYS *in production—it’s O(n) and blocks the single-threaded server.
Generic Commands
EXISTS key1 [key2 ...]: Returns the count of existing keys (O(1)).DEL key1 [key2 ...]: Deletes keys; returns the number deleted (O(1)).EXPIRE key seconds: Sets a TTL in seconds; returns 1 on success, 0 otherwise (O(1)).TTL key: Returns remaining TTL.-1means no expiration;-2means key doesn’t exist (O(1)).TYPE key: Returns the data type of the value stored atkey.
String-Specific Commands
APPEND key value: Appends to a string; creates key if missing. Returns new length.INCR key: Increments integer value by 1 (treats missing key as 0).DECR key: Decrements by 1.INCRBY key increment,DECRBY key decrement: Adjust by arbitrary integers.INCRBYFLOAT key increment: Supports floating-point adjustments.GETRANGE key start end: Extracts substring (inclusive, supports negative indices).SETRANGE key offset value: Overwrites part of a string; pads with\x00if needed.STRLEN key: Returns byte length of string value.
Advanced SET options:
SET key value [EX seconds | PX milliseconds] [NX | XX]NX: Set only if key doesn’t exist.XX: Set only if key exists.
Batch operations reduce network round trips:
MSET key1 val1 key2 val2 ...MGET key1 key2 ...
Data Types and Internal Encodings
All Redis keys are strings, but values support multiple types with optimized internal representations:
- String: Encoded as
int(for numeric strings),embstr(≤39 bytes), orraw(longer strings). - Hash: Uses
ziplistfor small hashes; switches tohashtablewhen thresholds are exceeded. - List: Historically used
ziplistorlinkedlist; since Redis 3.2, usesquicklist(a ziplist-backed linked list). - Set: Encoded as
intset(small sets of integers) orhashtable(larger or non-integer sets). - Sorted Set (ZSet): Uses
ziplistfor small sets;skiplistfor larger ones, enabling efficient range queries.
Use OBJECT ENCODING key to inspect the actual encoding.
Key Expiration Mechanism
Redis employs two complementary strategies:
- Lazy Expiration: Checks expiration only when a key is accessed. If expired, it’s deleted before returning a result.
- Periodic Expiration: Every 100ms, Redis samples a subset of expiring keys and deletes those that have past their TTL.
This hybrid approach balances CPU usage and memory efficiency without requiring full scans.
Why Redis Is Single-Threaded
Redis processes commands in a single thread to:
- Eliminate concurrency complexity (no locks or race conditions).
- Avoid CPU overhead from context switching.
- Leverage I/O multiplexing (e.g., epoll) to handle thousands of connections efficiently.
- Guarantee atomicity for individual commands.
- Maximize CPU cache locality for memory-bound operations.
However, long-running commands (e.g., KEYS *, large SMEMBERS) can block the entire server. Hence, O(n) operations on large datasets should be avoided.
Performance stems from in-memory storage, minimal command logic, and efficient event-driven I/O—not raw threading. For bulk deletion, FLUSHALL clears all database.