Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Understanding Redis Single-Threaded Architecture and Core Commands

Tech May 10 4

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. Returns nil if 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]). Avoid KEYS * 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. -1 means no expiration; -2 means key doesn’t exist (O(1)).
  • TYPE key: Returns the data type of the value stored at key.

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 \x00 if 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), or raw (longer strings).
  • Hash: Uses ziplist for small hashes; switches to hashtable when thresholds are exceeded.
  • List: Historically used ziplist or linkedlist; since Redis 3.2, uses quicklist (a ziplist-backed linked list).
  • Set: Encoded as intset (small sets of integers) or hashtable (larger or non-integer sets).
  • Sorted Set (ZSet): Uses ziplist for small sets; skiplist for larger ones, enabling efficient range queries.

Use OBJECT ENCODING key to inspect the actual encoding.

Key Expiration Mechanism

Redis employs two complementary strategies:

  1. Lazy Expiration: Checks expiration only when a key is accessed. If expired, it’s deleted before returning a result.
  2. 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.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.