I need to make a python backed for a web service Wordle game. It should have 1 global word for all users, that will be selected randomly from the list of words, it should have a session for each user with 5 tries(as wordle usually has) and after a susseccful wordle game for winning it should sent Pulsar message into specific topic to claim a points, with this session uuid as an idempotency key. To make sure that key is valid I think that session key should be generated based on the word + date + user_uuid (the key format is also uuid). The game itself will be made using websockets and FastAPI. To be able process games fast and make those horizontally scalable the session for each user should be stored in Redis as cache and processed there using locks. And only result is stored in DB(whether its a win or a loss.
Assistant
Creating a scalable Python backend for a Wordle-like web service involves several components, including real-time communication via WebSockets, session management with Redis, message queuing with Apache Pulsar, and persistent storage with a database. Below is a comprehensive guide on how to implement this using FastAPI, Redis, WebSockets, and Pulsar.
Table of Contents
Architecture Overview
Project Setup
Defining the Word Selection Logic
Session Management with Redis
WebSocket Implementation with FastAPI
Idempotency Key Generation
Pulsar Integration for Point Claims
Database Integration
Ensuring Horizontal Scalability
Complete Code Example
Conclusion
Architecture Overview
Word Selection: A global word is selected daily and shared across all users.
Sessions: Each user has a session with up to 5 attempts to guess the word.
WebSockets: Real-time communication between client and server using WebSockets.
Redis: Caches user sessions and manages concurrent access with locks.
Pulsar: Sends messages to claim points after a successful game.
Database: Stores only the game outcomes (win or loss).
[image: Architecture Diagram] open(Replace with an actual diagram if available)
Project Setup
1. Initialize the Project
Create a new directory for your project and set up a virtual environment.
bash
mkdir wordle-backend
cd wordle-backend
python3 -m venv venv
source venv/bin/activate
redis & aioredis: For interacting with Redis asynchronously.
apache-pulsar-client: For sending messages to Pulsar.
websockets: For handling WebSocket connections.
sqlalchemy & databases & asyncpg: For ORM and database interactions.
Defining the Word Selection Logic
Assume you have a list of valid words stored in a file or database.
1. Load Words
python
import random
from datetime import datetime
WORD_LIST = []
WORD_LENGTH = 5
def load_words(file_path: str):
global WORD_LIST
with open(file_path, 'r') as file:
WORD_LIST = [word.strip().lower() for word in file if len(word.strip()) == WORD_LENGTH]
def get_word_of_the_day() -> str:
# For simplicity, seed the random number generator with the current date
today = datetime.utcnow().date()
random.seed(today.toordinal()) # Ensures the same word every day
return random.choice(WORD_LIST)
2. Schedule Word Refresh (Optional)
If you want to reload or update the word list periodically, consider scheduling a task using APScheduler or similar.
Session Management with Redis
Use Redis to store each user's session data, including the number of attempts and the guessed words.
import json
def init_session(user_uuid: str, word: str):
session_key = f"session:{user_uuid}"
session_data = {
"word": word,
"attempts": 0,
"guesses": [],
"status": "ongoing" # could be "win" or "loss"
}
return session_data
async def get_session(user_uuid: str):
session_key = f"session:{user_uuid}"
data = await redis.get(session_key)
if data:
return json.loads(data)
else:
word = get_word_of_the_day()
session_data = init_session(user_uuid, word)
await redis.set(session_key, json.dumps(session_data))
return session_data
async def update_session(user_uuid: str, session_data: dict):
session_key = f"session:{user_uuid}"
await redis.set(session_key, json.dumps(session_data))
WebSocket Implementation with FastAPI
Create WebSocket endpoints to handle real-time communication.
python
from fastapi import WebSocket, WebSocketDisconnect
import uuid
@app.websocket("/ws/{user_uuid}")
async def websocket_endpoint(websocket: WebSocket, user_uuid: str):
await websocket.accept()
try:
while True:
data = await websocket.receive_text()
# Process the received guess
response = await process_guess(user_uuid, data)
await websocket.send_text(json.dumps(response))
except WebSocketDisconnect:
print(f"User {user_uuid} disconnected")
Idempotency Key Generation
Generate a unique session UUID combining the word, date, and user UUID.
python
import hashlib
def generate_session_uuid(word: str, date: str, user_uuid: str) -> str:
unique_str = f"{word}:{date}:{user_uuid}"
# Use SHA-256 hash and take first 32 characters to form a UUID-like string
hash_digest = hashlib.sha256(unique_str.encode()).hexdigest()[:32]
return str(uuid.UUID(hash_digest))
Pulsar Integration for Point Claims
After a successful game, send a message to Pulsar to claim points.
from fastapi import FastAPI
@app.on_event("startup")
async def startup_event():
await database.connect()
# Initialize Redis as before
@app.on_event("shutdown")
async def shutdown_event():
await database.disconnect()
# Close Redis as before
Stateless Servers: Ensure that the FastAPI application is stateless. All stateful data (sessions) are stored in Redis.
Redis as a Central Cache: Use Redis as a centralized store for session data, allowing multiple instances of your FastAPI app to access session information.
Pulsar for Asynchronous Processing: Use Pulsar to handle point claims asynchronously, decoupling the game logic from the point processing logic.
Database Scalability: Ensure your database can handle concurrent writes. If necessary, use read replicas or partitioning.
Load Balancing: Deploy your FastAPI application behind a load balancer to distribute incoming WebSocket connections across multiple instances.
Complete Code Example
Below is a simplified but complete example integrating the above components.
python
Notes:
Locking Mechanism: The above example uses a simple SETNX for locking. In production, consider using more robust locking mechanisms like Redlock to handle edge cases and ensure reliability.
Error Handling: Add comprehensive error handling for various scenarios, such as Redis outages, Pulsar failures, and database issues.
Security: Implement authentication and authorization to ensure that only legitimate users can access their sessions.
Scalability: Ensure that all instances of your FastAPI app connect to the same Redis and Pulsar instances or clusters.
Performance Optimizations: Cache the word of the day in memory if it doesn't change frequently to reduce Redis lookups.
Conclusion
This guide provides a structured approach to building a scalable Wordle-like backend using Python, FastAPI, WebSockets, Redis, Pulsar, and a relational database. By leveraging these technologies, you can ensure real-time responsiveness, efficient session management, and the ability to scale horizontally to handle a growing number of users. Remember to implement robust error handling, security measures, and thorough testing to ensure a reliable and secure application.