본문으로 건너뛰기
Skillpedia
API 및 서버 (백엔드)280k · #240

redis-patterns

하는 일

이 가이드는 빠른 데이터베이스인 Redis를 일반적인 프로그래밍 작업에 사용하도록 돕습니다. 데이터를 효율적으로 저장해 애플리케이션 속도를 높이고, 접근을 제어하며, 메시지를 보내는 방법을 보여 줍니다.

사용하는 경우

  • ✓캐싱으로 애플리케이션을 더 빠르게 만들고 싶을 때.
  • ✓사용자가 일정 시간 안에 어떤 행동을 하는 횟수를 제한할 때.
  • ✓한 번에 하나의 코드만 실행되도록 보장할 때.

스킬 링크

https://github.com/affaan-m/ECC/blob/main/pi/core/skills/redis-patterns/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/redis-patterns/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“Redis를 사용해 사용자 세션 정보를 안전하게 저장하려면 어떻게 해야 할까요?”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

문자열과 해시 같은 Redis 데이터 구조를 사용해 정보를 보관합니다. 더 복잡한 작업에는 특수 스크립트나 트랜잭션을 사용해 모든 것이 올바르게 일어나도록 합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

Redis Patterns

Quick reference for Redis best practices across common backend use cases.

How It Works

Redis is an in-memory data structure store that supports strings, hashes, lists, sets, sorted sets, streams, and more. Individual Redis commands are atomic on a single instance; multi-step workflows require Lua scripts, MULTI/EXEC transactions, or explicit synchronization to stay atomic. Data is optionally persisted via RDB snapshots or AOF logs. Clients communicate over TCP using the RESP protocol; connection pools are essential to avoid per-request handshake overhead.

When to Activate

  • Adding caching to an application
  • Implementing rate limiting or throttling
  • Building distributed locks or coordination
  • Setting up session or token storage
  • Using Pub/Sub or Redis Streams for messaging
  • Configuring Redis in production (pooling, eviction, clustering)

Data Structure Cheat Sheet

Use Case Structure Example Key
Simple cache String product:123
User session Hash session:abc
Leaderboard Sorted Set scores:weekly
Unique visitors Set visitors:2024-01-01
Activity feed List feed:user:456
Event stream Stream events:orders
Counters / rate limits String (INCR) ratelimit:user:123
Bloom filter / HLL HyperLogLog hll:pageviews

Core Patterns

Cache-Aside (Lazy Loading)

import redis
import json

r = redis.Redis(host='localhost', port=6379, decode_responses=True)

def get_product(product_id: int):
    cache_key = f"product:{product_id}"
    cached = r.get(cache_key)

    if cached:
        return json.loads(cached)

    product = db.query("SELECT * FROM products WHERE id = %s", product_id)
    r.setex(cache_key, 3600, json.dumps(product))  # TTL: 1 hour
    return product

Write-Through Cache

def update_product(product_id: int, data: dict):
    # Write to DB first
    db.execute("UPDATE products SET ... WHERE id = %s", product_id)

    # Immediately update cache
    cache_key = f"product:{product_id}"
    r.setex(cache_key, 3600, json.dumps(data))

Cache Invalidation

# Tag-based invalidation — group related keys under a set
def cache_product(product_id: int, category_id: int, data: dict):
    key = f"product:{product_id}"
    tag = f"tag:category:{category_id}"
    pipe = r.pipeline(transaction=True)
    pipe.setex(key, 3600, json.dumps(data))
    pipe.sadd(tag, key)
    pipe.expire(tag, 3600)
    pipe.execute()

def invalidate_category(category_id: int):
    tag = f"tag:category:{category_id}"
    keys = r.smembers(tag)
    if keys:
        r.delete(*keys)
    r.delete(tag)

Session Storage

import time
import uuid

def create_session(user_id: int, ttl: int = 86400) -> str:
    session_id = str(uuid.uuid4())
    key = f"session:{session_id}"
    pipe = r.pipeline(transaction=True)
    pipe.hset(key, mapping={
        "user_id": user_id,
        "created_at": int(time.time()),
    })
    pipe.expire(key, ttl)
    pipe.execute()
    return session_id

def get_session(session_id: str) -> dict | None:
    data = r.hgetall(f"session:{session_id}")
    return data if data else None

def delete_session(session_id: str):
    r.delete(f"session:{session_id}")

Rate Limiting

Fixed Window (Simple)

def is_rate_limited(user_id: int, limit: int = 100, window: int = 60) -> bool:
    key = f"ratelimit:{user_id}:{int(time.time()) // window}"
    pipe = r.pipeline(transaction=True)
    pipe.incr(key)
    pipe.expire(key, window)
    count, _ = pipe.execute()
    return count > limit

Sliding Window (Lua — Atomic)

-- sliding_window.lua
local key = KEYS[1]
local now = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local limit = tonumber(ARGV[3])

redis.call('ZREMRANGEBYSCORE', key, 0, now - window)
local count = redis.call('ZCARD', key)

if count < limit then
    -- Use unique member (now + sequence) to avoid collisions within the same millisecond
    local seq_key = key .. ':seq'
    local seq = redis.call('INCR', seq_key)
    redis.call('EXPIRE', seq_key, math.ceil(window / 1000))
    redis.call('ZADD', key, now, now .. '-' .. seq)
    redis.call('EXPIRE', key, math.ceil(window / 1000))
    return 1
end
return 0
sliding_window = r.register_script(open('sliding_window.lua').read())

def allow_request(user_id: int) -> bool:
    key = f"ratelimit:sliding:{user_id}"

…
자주 묻는 질문

Redis란 무엇인가요?

매우 빠른 접근을 위해 정보를 컴퓨터 메모리에 저장하는 데이터베이스입니다. 텍스트, 목록, 집합 같은 다양한 데이터 타입을 지원합니다.

커넥션 풀을 사용하는 이유는 무엇인가요?

애플리케이션이 필요할 때마다 Redis에 새 연결을 만드는 것은 느릴 수 있습니다. 커넥션 풀은 연결을 미리 준비해 두어 시간을 절약합니다.

분산 잠금이란 무엇인가요?

여러 애플리케이션이나 프로세스가 공유 자원에 동시에 접근하지 못하도록 한 번에 하나만 허용하는 신호와 같습니다. 충돌을 막습니다.

상세 정보

작성자의 원본 설명

Redis data structure patterns, caching strategies, distributed locks, rate limiting, pub/sub, and connection management for production applications. Use when adding caching, a distributed lock, rate limiting, or pub/sub with Redis, or when key design needs review.

repo: affaan-m/ECC

인기도

GitHub 스타
280k
순위
#240
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬