惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Threat Research - Cisco Blogs
S
Securelist
H
Heimdal Security Blog
Scott Helme
Scott Helme
D
Darknet – Hacking Tools, Hacker News & Cyber Security
The Hacker News
The Hacker News
C
CXSECURITY Database RSS Feed - CXSecurity.com
Spread Privacy
Spread Privacy
Cyberwarzone
Cyberwarzone
V
Vulnerabilities – Threatpost
C
Cybersecurity and Infrastructure Security Agency CISA
C
CERT Recently Published Vulnerability Notes
P
Proofpoint News Feed
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
人人都是产品经理
人人都是产品经理
C
Cisco Blogs
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Engineering at Meta
Engineering at Meta
Project Zero
Project Zero
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
有赞技术团队
有赞技术团队
T
Tailwind CSS Blog
Cisco Talos Blog
Cisco Talos Blog
Last Week in AI
Last Week in AI
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
O
OpenAI News
P
Proofpoint News Feed
Google Online Security Blog
Google Online Security Blog
Recent Announcements
Recent Announcements
Hacker News: Ask HN
Hacker News: Ask HN
美团技术团队
Stack Overflow Blog
Stack Overflow Blog
U
Unit 42
P
Privacy International News Feed
Google DeepMind News
Google DeepMind News
G
GRAHAM CLULEY
Apple Machine Learning Research
Apple Machine Learning Research
TaoSecurity Blog
TaoSecurity Blog
S
Security @ Cisco Blogs
C
Check Point Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Jina AI
Jina AI
S
Secure Thoughts
G
Google Developers Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
L
LINUX DO - 最新话题
T
Tenable Blog
Latest news
Latest news
I
InfoQ

Stonecharioteer on Tech

I Traced My Traffic Through a Home Tailscale Exit Node What Was I Reading Last? In Three Not-So-Easy Pieces Dogfooding Is Hard Code blocks in your books, finally GoForGo v0.9.0 Merrilin - We built an app to read books I use a Macbook now Data Structures & Algorithms - Preparing for Interviews Using a local DNS namespace for local service discovery Direction KOllector - Publishing KOReader Highlights gbt: branches touched in the last 24 hours A Soiree into Symbols in Ruby Some Smalltalk about Ruby Loops Ruby Blocks Returning from Ruby Blocks, Procs and Lambdas My Linux Laptop Finally Works: How Claude Helped Me Fix Years of Annoyances TIL: Watchexec - Modern File Watching for Development Workflows A Less Busy Mind GoForGo - Learn Go through live examples Migrating My Old Blog to Hugo with Claude The Qtile Window Manager: A Python-Powered Tiling Experience Read the RFCs that Built the Internet Py-x-Protobuf - Or How I Learned to Stop Worrying and Love Protocol Buffers Python Reverse a List New Beginnings Leaving ChainSafe Systems Screen Lock for Cinnamon Desktop using Zenity and Terminal Commands Crews Not Teams A System for Getting Better at LeetCode So Far So Rust Retrying HTTP Requests with Rust A Primer on Control Charts Learning Rust Explicit is Better than Implicit: Rust for Pythonistas Using Custom Delimiters in Jinja Templates TIL: Creating Fixed Length Iterables in Python Documentation Without Assumption Vagrant Python - A Reflection in 2022 Learning Golang No, A Virtual Machine Is Not Enough: Why Developers Need Native Linux Empathy in Tech For Those Who Came in Late A Weekend With PostgreSQL TIL: Gooey and Python Fire for Quick GUIs and CLIs TIL: 2ality - Dr. Axel Rauschmayer's JavaScript Blog TIL: MassDNS - High-Performance Bulk DNS Lookups TIL: Matomo Analytics, Google Tech Writing, Memory Programming, and NES TV Signals TIL: MontyDB - MongoDB Implemented in Python Returning to the Craft of Programming TIL: CPUFetch, OneFetch, and Learn CSS TIL: DNS Performance Testing and Pi-hole with Unbound TIL: Eli Bendersky's Blog, Awesome By Example, NoCoDB, and Martin Kleppmann TIL: CRDTs, Extreme HTTP Performance, and BYTEPATH Game TIL: AutoInvent, ASGI, Python Packaging, RAPIDS GPU Computing, and FlaskCon TIL: MangaDesk - Terminal Client for MangaDex TIL: McFly - Smart Shell History Search TIL: Siege Load Testing and Awesome FastAPI Resources TIL: Ventoy Bootable USB and Justniffer Network Analysis TIL: CLI Code Review, Git Split Diffs, and Internal Combustion Engine TIL: Benford's Law, Web Security Headers, Event Sourcing, and Mozilla Security Guidelines How to Write Documentation - The README.md File The Importance of Documentation TIL: NNgroup UX Research, SponsorBlock, and Labella Python Library TIL: The Little Book of Rust Macros and Rust Performance Book TIL: Git-Bug Distributed Issue Tracker and Omni Kubernetes Monitoring TIL: Zellij - Modern Terminal Multiplexer TIL: How Discord Handles 2.5 Million Concurrent Voice Users TIL: Volumio - The Audiophile Music Player TIL: Areopagitica - Milton's Defense of Free Speech TIL: Fast Node Manager, Zoxide Smart CD, Technical Writing, PyO3, and Qubes OS TIL: Slurm Workload Manager for HPC Clusters TIL: Data Visualization Guide and Oso Authorization Academy TIL: CORS Deep Dive, Piku Tiny PaaS, Rust Strings, and Deno Standard Library TIL: Raspberry Pi OS Development, Vim Beginner Guide, Password Management, and QueryBook TIL: uBlock Origin Performance Optimization on Firefox TIL: Breaking PostgreSQL at Scale and LeetCode Problem Patterns TIL: Awesome Tmux Resources for Terminal Multiplexing TIL: Grit - A Multitree-Based Personal Task Manager TIL: Lens 4.2 Kubernetes IDE, Shell Scripting Guide, and Dark HTTP Server Do The Job You Hate So You Won't Hate The Job You Love TIL: Innernet VPN Solution and NoteCalc Calculator App TIL: Argo CD for GitOps and Lens Kubernetes IDE TIL: Modern Rust CLI Tools - System Monitoring, HTTP Requests, and DNS TIL: tz - A Time Zone Helper Tool TIL: Distributed Systems Education, Fallacies, and Self-Hosted Internet Archiving TIL: Real-Time Voice Cloning Technology TIL: ChartMuseum for Helm, AMD's Corporate Journey, and Kubernetes Pod Scaling TIL: Docker and Kubernetes Tools - Whaler, Descheduler, and Dive TIL: Post-Mortem Collection, Terminal Plotting, and Technical Twitter TIL: Dark Mode Toggle Web Component by Google Chrome Labs TIL: Python eval(), exec(), and compile() Functions TIL: Camelot PDF Tables, PostgreSQL Row Level Security, Zerodha Varsity, and Write Yourself a Git TIL: fuser Command for Process and File Investigation TIL: i Hate Regex - The Ultimate Regex Cheat Sheet TIL: Dolt - Git for Data and Database Version Control TIL: x86 Assembly Programming and SafeEyes Break Reminder TIL: Comprehensive Distributed Systems Reading List TIL: Cosmopolitan C Library, Distributed Systems Book, High Performance Browser Networking, and Rust Roguelike Tutorial
TIL: Redis Network Model and Internal Architecture
2021-02-20 · via Stonecharioteer on Tech

Redis Network Model Analysis

Detailed analysis on the source code of redis network model

Deep dive into how Redis achieves exceptional performance through its network architecture:

Event-Driven Architecture:

Single-Threaded Event Loop:

  • Main Thread: All Redis operations run in a single thread
  • Non-blocking I/O: Uses epoll/kqueue for efficient I/O multiplexing
  • Event Processing: Commands processed sequentially without context switching
  • Atomicity: Single-threaded nature ensures atomic operations

Event Types:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// File events for network I/O
#define AE_READABLE     1   // Socket ready for reading
#define AE_WRITABLE     2   // Socket ready for writing

// Time events for periodic tasks
typedef struct aeTimeEvent {
    long long id;           // Time event identifier
    long when_sec;          // When to fire (seconds)
    long when_ms;           // When to fire (milliseconds)
    aeTimeProc *timeProc;   // Time event handler
} aeTimeEvent;

Network I/O Implementation:

Client Connection Handling:

  1. Accept Phase: New client connections accepted
  2. Read Phase: Commands read from client sockets
  3. Process Phase: Commands executed in Redis core
  4. Write Phase: Responses written back to clients
  5. Cleanup Phase: Closed connections handled

Buffer Management:

1
2
3
4
5
6
7
typedef struct client {
    int fd;                 // Client socket file descriptor
    sds querybuf;           // Input buffer for commands
    list *reply;            // Output buffer list
    unsigned long reply_bytes; // Bytes in output buffer
    size_t querybuf_peak;   // Peak query buffer size
} client;

Performance Optimizations:

Pipeline Support:

  • Batch Processing: Multiple commands in single network round-trip
  • Reduced Latency: Fewer network calls for better performance
  • Buffer Reuse: Efficient memory management for pipelined requests

Memory Efficiency:

  • Zero-Copy: Direct buffer manipulation where possible
  • Pooled Buffers: Reuse of network buffers
  • Lazy Deletion: Deferred cleanup of large objects

Redis Under the Hood

Redis: under the hood

Comprehensive exploration of Redis internal data structures and algorithms:

Core Data Structures:

String Implementation:

1
2
3
4
5
struct sdshdr {
    int len;        // String length
    int free;       // Available space
    char buf[];     // Actual string data
};

Features:

  • Dynamic Sizing: Automatic growth and shrinkage
  • Binary Safe: Can store any byte sequence
  • Memory Efficient: Minimal overhead compared to C strings
  • O(1) Length: Length stored, not calculated

Hash Table (Dict):

1
2
3
4
5
6
typedef struct dict {
    dictType *type;     // Type-specific functions
    void *privdata;     // Private data
    dictht ht[2];       // Two hash tables for rehashing
    int rehashidx;      // Rehashing progress (-1 if not rehashing)
} dict;

Rehashing Strategy:

  • Incremental Rehashing: Gradual migration to avoid blocking
  • Progressive: Few entries moved per operation
  • Dual Tables: Old and new tables coexist during rehashing

Advanced Features:

Expiration Mechanism:

1
2
3
4
5
6
// Expiration strategies
#define EXPIRE_STRATEGY_ACTIVE    1  // Active expiration
#define EXPIRE_STRATEGY_PASSIVE   2  // Lazy expiration

// Expire dictionary tracks TTL
dict *expires;  // Maps keys to expiration times

Implementation:

  • Active Expiration: Background task removes expired keys
  • Passive Expiration: Keys checked on access
  • Sampling: Random sampling to find expired keys efficiently

Memory Management:

  • Object Encoding: Different encodings for memory efficiency
  • Reference Counting: Shared objects for memory savings
  • Copy-on-Write: Efficient forking for persistence

Persistence Models:

RDB (Redis Database) Snapshots:

  • Fork-based: Child process handles disk I/O
  • Compressed: Efficient binary format
  • Point-in-time: Consistent snapshots
  • Configurable: Various trigger conditions

AOF (Append Only File):

  • Command Logging: Every write command logged
  • Replayable: Reconstruct state by replaying commands
  • Rewriting: Periodic compaction of log files
  • Fsync Options: Different durability guarantees

Scaling Patterns:

Replication:

Master ──┬── Slave 1
         ├── Slave 2
         └── Slave N

Features:

  • Asynchronous: Non-blocking replication
  • Partial Resync: Resume from disconnection point
  • Read Scaling: Distribute read load across replicas

Clustering:

Cluster Node 1 ─┬─ Hash Slots 0-5460
Cluster Node 2 ─┼─ Hash Slots 5461-10922
Cluster Node 3 ─┴─ Hash Slots 10923-16383

Implementation:

  • Hash Slots: 16384 slots distributed across nodes
  • Client-side Routing: Clients calculate target node
  • Automatic Failover: Master failures handled automatically
  • Resharding: Live migration of slots between nodes

Performance Characteristics:

Operation Complexity:

GET/SET:        O(1)
LPUSH/RPUSH:    O(1)
LRANGE:         O(S+N) where S=start, N=elements
SADD:           O(1)
SINTER:         O(N*M) where N=smallest set
ZADD:           O(log(N))
ZRANGE:         O(log(N)+M) where M=elements returned

Memory Usage:

  • Overhead: ~20-30% overhead for Redis objects
  • Encoding Optimization: Automatic selection of efficient encodings
  • Compression: Option to trade CPU for memory savings

Production Considerations:

Configuration Tuning:

# Memory
maxmemory 2gb
maxmemory-policy allkeys-lru

# Persistence
save 900 1      # Save if 1 key changed in 900 seconds
save 300 10     # Save if 10 keys changed in 300 seconds
save 60 10000   # Save if 10000 keys changed in 60 seconds

# Network
tcp-backlog 511
timeout 0
tcp-keepalive 300

Monitoring Metrics:

  • Memory Usage: Watch for memory pressure
  • Command Latency: Monitor P99 latencies
  • Connection Count: Track client connections
  • Persistence Metrics: RDB/AOF performance
  • Replication Lag: Master-slave synchronization delay

Redis’s architecture demonstrates how careful design of data structures, memory management, and I/O handling can create exceptionally high-performance systems while maintaining simplicity and reliability.