Senior
What will the updated Redis schema with timeout-worker for time-limited games look like?
sobes.tech AI
Answer from AI
For time-limited games in Redis, a scheme with keys that automatically expire (TTL) and a separate worker that monitors expiration and handles timeouts can be used.
The updated scheme might look like this:
- A key with a unique ID is created for each game session and a TTL equal to the time limit is set.
- The worker subscribes to key expiration events (using Redis Keyspace Notifications).
- When a key expires, the worker receives a notification and executes the game-ending logic (e.g., determines the winner, updates statistics).
Example of setting a TTL key in Go:
err := redisClient.Set(ctx, "game:session:12345", "active", time.Minute*5).Err()
if err != nil {
// handle error
}
The worker listens for expiration events:
pubsub := redisClient.PSubscribe(ctx, "__keyevent@0__:expired")
for msg := range pubsub.Channel() {
if strings.HasPrefix(msg.Payload, "game:session:") {
sessionID := strings.TrimPrefix(msg.Payload, "game:session:")
// handle session timeout for sessionID
}
}
This approach allows efficient management of game times and reacting to timeouts without constant polling.