0Pricing
Redis Caching & Messaging (Pub/Sub, Streams) · 강의

Redis를 사용한 세션 관리

애플리케이션의 안정성을 높이도록 Redis를 사용해 견고하고 확장 가능한 사용자 세션 저장소를 구현합니다.

Redis를 사용한 세션 관리은(는) CoddyKit의 무료 Redis Caching & Messaging (Pub/Sub, Streams) 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Redis Caching & Messaging (Pub/Sub, Streams) 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Redis Caching & Messaging (Pub/Sub, Streams) 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

What are User Sessions?

User sessions are how web applications remember you! When you log in, add items to a cart, or navigate pages, your app tracks your state using a session.

Traditionally, sessions might be stored directly on the web server's memory or via small files (cookies) on your browser. This works for simple setups, but can become a bottleneck.

Why Redis for Sessions?

As applications grow, traditional session storage faces challenges:

  • Scalability: If you have multiple web servers, how do they all know about the same user's session?
  • Reliability: What happens if a server crashes and all in-memory sessions are lost?
  • Performance: Retrieving session data quickly is crucial for a smooth user experience.

Redis solves these by providing a fast, centralized, and persistent store for session data, accessible by all your application instances.

Storing Session Data in Redis

The best way to store session data in Redis is often using a Hash. A Redis Hash is like a small dictionary, perfect for holding multiple key-value pairs (your session attributes) under a single session ID.

We'll use a unique session ID (e.g., a UUID) as the main Redis key, like session:your_session_id, and inside that, store attributes like userId, username, loginTime, etc.

Creating a User Session

When a user logs in, your application generates a unique session ID. Then, it stores essential user information in Redis, along with a Time-To-Live (TTL) for automatic expiration.

Try running this Python example to create a new session:

import redis
import uuid
import time

r = redis.Redis(decode_responses=True)

def create_session(user_id, username):
    session_id = str(uuid.uuid4())
    session_key = f"session:{session_id}"
    r.hset(session_key, mapping={
        "userId": user_id,
        "username": username,
        "loginTime": int(time.time())
    })
    r.expire(session_key, 3600) # Session expires in 1 hour (3600 seconds)
    print(f"Created session {session_id} for {username}")
    return session_id

if __name__ == "__main__":
    new_session_id = create_session("101", "Alice")
    print(f"New session ID: {new_session_id}")

Accessing Session Data

Once a session is created, your application needs to retrieve its data using the session ID (often sent via a cookie). We use HGETALL to fetch all attributes of a session Hash.

Run this code to see how to retrieve session data. Replace 'abc12345' with a session ID you created or a placeholder:

import redis

r = redis.Redis(decode_responses=True)

def get_session_data(session_id):
    session_key = f"session:{session_id}"
    data = r.hgetall(session_key)
    if data:
        print(f"Session {session_id} data: {data}")
    else:
        print(f"Session {session_id} not found or expired.")
    return data

if __name__ == "__main__":
    # Replace with an actual session ID from previous step or a dummy one
    get_session_data("abc12345") 

Modifying Session Data

User actions might require updating session data, such as changing preferences or recording the lastActivity timestamp. It's also good practice to extend the session's expiration (refresh the TTL) with each activity.

Here's how to update an attribute and refresh the session's TTL:

import redis
import time

r = redis.Redis(decode_responses=True)

def update_session(session_id, key, value):
    session_key = f"session:{session_id}"
    r.hset(session_key, key, value)
    r.expire(session_key, 3600) # Refresh TTL for 1 hour
    print(f"Updated '{key}' in session {session_id}. TTL refreshed.")

if __name__ == "__main__":
    # Replace with an actual session ID
    update_session("abc12345", "lastActivity", int(time.time()))

Ending a User Session (Logout)

When a user logs out, or their session needs to be invalidated (e.g., due to inactivity), you simply delete the session key from Redis. This immediately removes all associated session data.

The DEL command is straightforward for this:

import redis

r = redis.Redis(decode_responses=True)

def delete_session(session_id):
    session_key = f"session:{session_id}"
    deleted_count = r.delete(session_key)
    if deleted_count > 0:
        print(f"Session {session_id} deleted successfully.")
    else:
        print(f"Session {session_id} not found.")

if __name__ == "__main__":
    # Replace with an actual session ID
    delete_session("abc12345")

Managing Session Expiration

Redis's Time-To-Live (TTL) feature is fundamental for session management. It ensures sessions are automatically cleaned up after a set period, saving memory and enhancing security by preventing stale sessions from lingering indefinitely.

You can use EXPIRE to set a TTL (as seen in previous examples) and TTL to check the remaining time. A return value of -2 means the key doesn't exist, and -1 means it exists but has no expiration.

import redis
import time

r = redis.Redis(decode_responses=True)

def check_session_ttl(session_id):
    session_key = f"session:{session_id}"
    ttl = r.ttl(session_key)
    if ttl == -2:
        print(f"Session {session_id} does not exist.")
    elif ttl == -1:
        print(f"Session {session_id} exists but has no expiration.")
    else:
        print(f"Session {session_id} expires in {ttl} seconds.")

if __name__ == "__main__":
    # Create a temporary session for demonstration
    temp_session_id = "temp_session_123"
    r.hset(f"session:{temp_session_id}", "testKey", "testValue")
    r.expire(f"session:{temp_session_id}", 60) # Expires in 60 seconds
    print(f"Created temporary session {temp_session_id} with 60s TTL.")
    time.sleep(1) # Wait a moment
    check_session_ttl(temp_session_id)
    r.delete(f"session:{temp_session_id}") # Clean up

Securing Your Sessions

While Redis provides robust storage, overall session security also relies on your application's practices:

  • Strong Session IDs: Always generate cryptographically secure, random IDs (like UUIDs) to prevent prediction.
  • HTTPS Only: Ensure all communication carrying session IDs (e.g., via cookies) is over HTTPS to prevent eavesdropping.
  • HttpOnly & Secure Flags: For cookies, use HttpOnly to prevent client-side script access and Secure to send only over HTTPS.
  • Short TTLs: Keep session expiration times as short as reasonably possible for user experience, balanced with security.
  • Re-authenticate for sensitive actions: For critical operations (e.g., changing passwords), always prompt for the user's password again.

Quick Check

Consider a web application using Redis for session management. A user logs in, performs some actions, and then logs out. Which sequence of Redis commands best represents these operations?

Recap & Next Steps

In this lesson, you learned how Redis excels at managing user sessions, offering a scalable and reliable alternative to traditional methods.

  • We explored using Redis Hashes to store diverse session attributes efficiently.
  • You practiced commands like HSET, HGETALL, EXPIRE, and DEL for managing the entire session lifecycle.
  • The importance of Time-To-Live (TTL) for automatic session cleanup and security was highlighted.
  • We also touched upon critical security considerations for handling sessions effectively.

By leveraging Redis, your applications can handle user sessions efficiently, even under high load, providing a consistent experience across multiple servers.

자주 묻는 질문

“Redis를 사용한 세션 관리” 강의는 무료인가요?

네 — “Redis를 사용한 세션 관리” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Redis Caching & Messaging (Pub/Sub, Streams) 강의 전체를 잠금 해제할 수 있습니다. Redis Caching & Messaging (Pub/Sub, Streams) 강의에는 총 4개의 강의가 포함되어 있습니다.

“Redis를 사용한 세션 관리”에서 뭘 배우나요?

애플리케이션의 안정성을 높이도록 Redis를 사용해 견고하고 확장 가능한 사용자 세션 저장소를 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 Redis Caching & Messaging (Pub/Sub, Streams)을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Redis Caching & Messaging (Pub/Sub, Streams)을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Redis Caching & Messaging (Pub/Sub, Streams)은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“Redis를 사용한 세션 관리” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Redis Caching & Messaging (Pub/Sub, Streams) 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Redis Caching & Messaging (Pub/Sub, Streams) 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 고급 캐시 패턴
  2. Redis를 사용한 세션 관리
  3. 요청 빈도 제한 및 안티패턴
  4. 캐시 무효화 전략
← Redis Caching & Messaging (Pub/Sub, Streams)(으)로 돌아가기