
Redis Beyond Caching: 7 Powerful Patterns You Should Know
Redis is more than a cache. It's a Swiss Army knife for distributed systems. Here are 7 patterns that solve real problems. 1. Rate Limiting import redis import time r = redis . Redis () def is_rate_limited ( user_id : str , max_requests : int = 100 , window : int = 60 ) -> bool : key = f " rate: { user_id } : { int ( time . time ()) // window } " current = r . incr ( key ) if current == 1 : r . expire ( key , window ) return current > max_requests # Usage if is_rate_limited ( " user_123 " ): raise HTTPException ( status_code = 429 , detail = " Too many requests " ) 2. Distributed Locking Prevent race conditions across multiple servers: import uuid def acquire_lock ( lock_name : str , timeout : int = 10 ) -> str | None : lock_id = str ( uuid . uuid4 ()) if r . set ( f " lock: { lock_name } " , lock_id , nx = True , ex = timeout ): return lock_id return None def release_lock ( lock_name : str , lock_id : str ) -> bool : pipe = r . pipeline ( True ) key = f " lock: { lock_name } " try : p
Continue reading on Dev.to Tutorial
Opens in a new tab




