0d8f5b9600
- Add /health and /ready endpoints for load balancer health checks - Replace in-memory JWT token cache with Redis for multi-replica support - Reduce DB connection pool from 100 to 25 connections per replica - Add distributed rate limiting (100 req/min + 20 burst) using Redis - Implement circuit breakers for DB and Redis to prevent cascading failures This enables the service to scale horizontally with multiple replicas behind a load balancer without exhausting database connections or maintaining separate token caches per instance.
65 lines
1.5 KiB
Go
65 lines
1.5 KiB
Go
package redisclient
|
|
|
|
import (
|
|
"authorization/helper"
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"time"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
var RDB *redis.Client
|
|
|
|
// RedisCircuitBreaker protects Redis operations
|
|
var RedisCircuitBreaker *helper.CircuitBreaker
|
|
|
|
func Init() {
|
|
redisHost := os.Getenv("REDIS_HOST")
|
|
if redisHost == "" {
|
|
redisHost = "localhost"
|
|
}
|
|
|
|
redisPort := os.Getenv("REDIS_PORT")
|
|
if redisPort == "" {
|
|
redisPort = "6379"
|
|
}
|
|
|
|
redisPassword := os.Getenv("REDIS_PASSWORD")
|
|
if redisPassword == "" {
|
|
redisPassword = ""
|
|
}
|
|
|
|
// Configure Redis client with security settings
|
|
opts := &redis.Options{
|
|
Addr: fmt.Sprintf("%s:%s", redisHost, redisPort),
|
|
Password: redisPassword,
|
|
DB: 0,
|
|
DisableIndentity: true, // Disable client-side caching to prevent protocol confusion
|
|
IdentitySuffix: "", // Disable identity suffix
|
|
}
|
|
|
|
RDB = redis.NewClient(opts)
|
|
|
|
// Initialize circuit breaker
|
|
RedisCircuitBreaker = helper.NewCircuitBreaker("redis", 5, 2*time.Second)
|
|
|
|
// Test connection with authentication using circuit breaker
|
|
ctx := context.Background()
|
|
err := RedisCircuitBreaker.Call(func() error {
|
|
_, err := RDB.Ping(ctx).Result()
|
|
return err
|
|
})
|
|
if err != nil {
|
|
panic(fmt.Sprintf("Could not connect to Redis: %v", err))
|
|
}
|
|
|
|
// Log connection security status
|
|
if redisPassword != "" {
|
|
fmt.Println("✓ Redis connection secured with password authentication")
|
|
} else {
|
|
fmt.Println("⚠ WARNING: Redis connection without password - security risk!")
|
|
}
|
|
}
|