LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows
Python ai-agentsdata-engineeringdocument-aigenerative-aiidpjson-extractionllmmcp-serverocrpdf-extractionprompt-engineeringstructured-output
UN-3307 [FEAT] Redis Sentinel HA support (#1838)
Chandrasekharan Ma6d8e80e0301
diff --git a/backend/backend/settings/base.py b/backend/backend/settings/base.pyindex 97e5be789..d1d935b91 100644--- a/backend/backend/settings/base.py+++ b/backend/backend/settings/base.py@@ -12,7 +12,7 @@ https://docs.djangoproject.com/en/4.2/ref/settings/import loggingimport osfrom pathlib import Path-from urllib.parse import urlparse+from urllib.parse import quote, urlparseimport httpxfrom dotenv import find_dotenv, load_dotenv@@ -441,23 +441,75 @@ TEMPLATES = [WSGI_APPLICATION = "backend.wsgi.application"-# SocketIO connection manager-SOCKET_IO_MANAGER_URL = f"redis://{REDIS_HOST}:{REDIS_PORT}"+# Redis Sentinel HA Configuration (LLMW pattern)+# Single boolean flag; in Sentinel mode REDIS_HOST/PORT point to the Sentinel service+REDIS_SENTINEL_MODE = (+ os.environ.get("REDIS_SENTINEL_MODE", "False").strip().lower() == "true"+)-CACHES = {- "default": {- "BACKEND": "django_redis.cache.RedisCache",- "LOCATION": f"redis://{REDIS_HOST}:{REDIS_PORT}",- "OPTIONS": {- "CLIENT_CLASS": "django_redis.client.DefaultClient",- "SERIALIZER": "django_redis.serializers.json.JSONSerializer",- "DB": REDIS_DB,- "USERNAME": REDIS_USER,- "PASSWORD": REDIS_PASSWORD,- },- "KEY_FUNCTION": "utils.redis_cache.custom_key_function",+REDIS_SENTINEL_MASTER_NAME = os.environ.get("REDIS_SENTINEL_MASTER_NAME", "mymaster")++if REDIS_SENTINEL_MODE:+ _sentinel_kwargs = {}+ if REDIS_PASSWORD:+ _sentinel_kwargs["password"] = REDIS_PASSWORD+ if REDIS_USER:+ _sentinel_kwargs["username"] = REDIS_USER++ _redis_db = REDIS_DB or "0"++ # SocketIO connection manager (Kombu Sentinel URL format)+ _cred_prefix = ""+ if REDIS_USER and REDIS_PASSWORD:+ _cred_prefix = f"{quote(REDIS_USER, safe='')}:{quote(REDIS_PASSWORD, safe='')}@"+ elif REDIS_PASSWORD:+ _cred_prefix = f":{quote(REDIS_PASSWORD, safe='')}@"+ SOCKET_IO_MANAGER_URL = (+ f"sentinel://{_cred_prefix}{REDIS_HOST}:{REDIS_PORT}/{_redis_db}"+ )+ SOCKET_IO_TRANSPORT_OPTIONS = {"master_name": REDIS_SENTINEL_MASTER_NAME}++ # django-redis expects username in the LOCATION URL for ACL auth+ _user_prefix = f"{REDIS_USER}@" if REDIS_USER else ""+ CACHES = {+ "default": {+ "BACKEND": "django_redis.cache.RedisCache",+ "LOCATION": f"redis://{_user_prefix}{REDIS_SENTINEL_MASTER_NAME}/{_redis_db}",+ "OPTIONS": {+ "CLIENT_CLASS": "django_redis.client.SentinelClient",+ "SENTINELS": [(REDIS_HOST, int(REDIS_PORT))],+ "SENTINEL_KWARGS": _sentinel_kwargs,+ "DB": int(_redis_db),+ "PASSWORD": REDIS_PASSWORD,+ "SERIALIZER": "django_redis.serializers.json.JSONSerializer",+ },+ "KEY_FUNCTION": "utils.redis_cache.custom_key_function",+ }+ }+else:+ # SocketIO connection manager (standalone)+ _cred_prefix = ""+ if REDIS_USER and REDIS_PASSWORD:+ _cred_prefix = f"{quote(REDIS_USER, safe='')}:{quote(REDIS_PASSWORD, safe='')}@"+ elif REDIS_PASSWORD:+ _cred_prefix = f":{quote(REDIS_PASSWORD, safe='')}@"+ SOCKET_IO_MANAGER_URL = f"redis://{_cred_prefix}{REDIS_HOST}:{REDIS_PORT}"+ SOCKET_IO_TRANSPORT_OPTIONS = {}++ CACHES = {+ "default": {+ "BACKEND": "django_redis.cache.RedisCache",+ "LOCATION": f"redis://{REDIS_HOST}:{REDIS_PORT}",+ "OPTIONS": {+ "CLIENT_CLASS": "django_redis.client.DefaultClient",+ "SERIALIZER": "django_redis.serializers.json.JSONSerializer",+ "DB": int(REDIS_DB) if REDIS_DB else 0,+ "USERNAME": REDIS_USER,+ "PASSWORD": REDIS_PASSWORD,+ },+ "KEY_FUNCTION": "utils.redis_cache.custom_key_function",+ }}-}SESSION_ENGINE = "django.contrib.sessions.backends.cached_db"diff --git a/backend/sample.env b/backend/sample.envindex 909f02e1f..41246c704 100644--- a/backend/sample.env+++ b/backend/sample.env@@ -42,6 +42,12 @@ REDIS_RETRY_MAX_ATTEMPTS=4# Handles: network blips, Redis restarts (3-5s), connection pool exhaustionREDIS_RETRY_BACKOFF_FACTOR=0.5+# Redis Sentinel mode - set to True for HA deployments (K8s only)+# When True: point REDIS_HOST to Sentinel K8s service DNS, REDIS_PORT to 26379+# REDIS_PASSWORD is reused for Sentinel auth.+REDIS_SENTINEL_MODE=False+REDIS_SENTINEL_MASTER_NAME=mymaster+# Connector OAuthSOCIAL_AUTH_EXTRA_DATA_EXPIRATION_TIME_IN_SECOND=3600GOOGLE_OAUTH2_KEY=diff --git a/backend/utils/cache_service.py b/backend/utils/cache_service.pyindex a649eca5e..ea6e4278b 100644--- a/backend/utils/cache_service.py+++ b/backend/utils/cache_service.py@@ -7,6 +7,8 @@ from django.conf import settingsfrom django.core.cache import cachefrom django_redis import get_redis_connection+from unstract.core.cache.redis_client import create_redis_client+redis_cache = get_redis_connection("default")logger = logging.getLogger(__name__)@@ -66,15 +68,7 @@ class CacheService:# Use specified DB or default connectionif db is not None:- import redis-- redis_connection = redis.Redis(- host=settings.REDIS_HOST,- port=settings.REDIS_PORT,- db=db,- username=getattr(settings, "REDIS_USER", None),- password=getattr(settings, "REDIS_PASSWORD", None),- )+ redis_connection = create_redis_client(decode_responses=False, db=db)else:redis_connection = redis_cachediff --git a/backend/utils/log_events.py b/backend/utils/log_events.pyindex 3e11c8fcf..898049dbb 100644--- a/backend/utils/log_events.py+++ b/backend/utils/log_events.py@@ -3,17 +3,21 @@ import loggingimport osfrom typing import Any-import redisimport socketiofrom django.conf import settingsfrom django.core.wsgi import WSGIHandler+from unstract.core.cache.redis_client import create_redis_clientfrom unstract.core.data_models import LogDataDTOfrom unstract.core.log_utils import get_validated_log_data, store_execution_logfrom utils.constants import ExecutionLogConstantslogger = logging.getLogger(__name__)+_kombu_kwargs: dict[str, Any] = {"url": settings.SOCKET_IO_MANAGER_URL}+if getattr(settings, "SOCKET_IO_TRANSPORT_OPTIONS", None):+ _kombu_kwargs["transport_options"] = settings.SOCKET_IO_TRANSPORT_OPTIONS+sio = socketio.Server(# Allowed values: {threading, eventlet, gevent, gevent_uwsgi}async_mode="threading",@@ -21,15 +25,17 @@ sio = socketio.Server(logger=False,engineio_logger=False,always_connect=True,- client_manager=socketio.KombuManager(url=settings.SOCKET_IO_MANAGER_URL),+ client_manager=socketio.KombuManager(**_kombu_kwargs),)-redis_conn = redis.Redis(- host=settings.REDIS_HOST,- port=int(settings.REDIS_PORT),- username=settings.REDIS_USER,- password=settings.REDIS_PASSWORD,-)+_redis_conn = None+++def _get_redis_conn():+ global _redis_conn+ if _redis_conn is None:+ _redis_conn = create_redis_client(decode_responses=False)+ return _redis_conn@sio.event@@ -90,7 +96,7 @@ def _store_execution_log(data: dict[str, Any]) -> None:"""Store execution log in database (backward compatibility wrapper)."""store_execution_log(data=data,- redis_client=redis_conn,+ redis_client=_get_redis_conn(),log_queue_name=ExecutionLogConstants.LOG_QUEUE_NAME,is_enabled=ExecutionLogConstants.IS_ENABLED,)diff --git a/platform-service/sample.env b/platform-service/sample.envindex 54eec703c..72ea02d19 100644--- a/platform-service/sample.env+++ b/platform-service/sample.env@@ -8,6 +8,12 @@ REDIS_PORT=6379REDIS_USERNAME=defaultREDIS_PASSWORD=+# Redis Sentinel mode - set to True for HA deployments (K8s only)+# When True: point REDIS_HOST to Sentinel K8s service DNS, REDIS_PORT to 26379+# REDIS_PASSWORD is reused for Sentinel auth.+REDIS_SENTINEL_MODE=False+REDIS_SENTINEL_MASTER_NAME=mymaster+# Backend DBPG_BE_HOST=unstract-dbPG_BE_PORT=5432diff --git a/platform-service/src/unstract/platform_service/extensions.py b/platform-service/src/unstract/platform_service/extensions.pyindex d84740579..75a073a5f 100644--- a/platform-service/src/unstract/platform_service/extensions.py+++ b/platform-service/src/unstract/platform_service/extensions.py@@ -5,41 +5,30 @@ from typing import Anyimport redisfrom peewee import PostgresqlDatabase-db = PostgresqlDatabase(None)+from unstract.core.cache.redis_client import create_redis_client-# Redis connection pool (initialized lazily)-_redis_pool: redis.ConnectionPool | None = None+db = PostgresqlDatabase(None)--def get_redis_pool() -> redis.ConnectionPool:- """Get or create the Redis connection pool.-- Returns:- redis.ConnectionPool: Shared connection pool for Redis operations.- """- global _redis_pool- if _redis_pool is None:- # Import here to avoid circular imports- from unstract.platform_service.env import Env-- _redis_pool = redis.ConnectionPool(- host=Env.REDIS_HOST,- port=Env.REDIS_PORT,- username=Env.REDIS_USERNAME,- password=Env.REDIS_PASSWORD,- max_connections=10,- decode_responses=False,- )- return _redis_pool+# Lazy singleton — avoids import-time Redis connection that blocks startup+_redis_client: redis.Redis | None = Nonedef get_redis_client() -> redis.Redis:- """Get a Redis client using the shared connection pool.+ """Get a Redis client, with Sentinel support and connection pooling.++ In standalone mode, uses a ConnectionPool with max_connections=10.+ In Sentinel mode, master_for() manages its own pooling.Returns:redis.Redis: Redis client instance."""- return redis.Redis(connection_pool=get_redis_pool())+ global _redis_client+ if _redis_client is None:+ _redis_client = create_redis_client(+ decode_responses=False,+ max_connections=10,+ )+ return _redis_client@contextmanagerdiff --git a/prompt-service/sample.env b/prompt-service/sample.envindex ddfbb5764..01d021f9d 100644--- a/prompt-service/sample.env+++ b/prompt-service/sample.env@@ -12,6 +12,12 @@ REDIS_PORT=6379REDIS_PASSWORD=""REDIS_USER=default+# Redis Sentinel mode - set to True for HA deployments (K8s only)+# When True: point REDIS_HOST to Sentinel K8s service DNS, REDIS_PORT to 26379+# REDIS_PASSWORD is reused for Sentinel auth.+REDIS_SENTINEL_MODE=False+REDIS_SENTINEL_MASTER_NAME=mymaster+# LoggingLOG_LEVEL=INFOdiff --git a/runner/sample.env b/runner/sample.envindex 723bc8961..afb58aae1 100644--- a/runner/sample.env+++ b/runner/sample.env@@ -42,6 +42,12 @@ REDIS_PORT=6379REDIS_USER=defaultREDIS_PASSWORD=+# Redis Sentinel mode - set to True for HA deployments (K8s only)+# When True: point REDIS_HOST to Sentinel K8s service DNS, REDIS_PORT to 26379+# REDIS_PASSWORD is reused for Sentinel auth.+REDIS_SENTINEL_MODE=False+REDIS_SENTINEL_MASTER_NAME=mymaster+# Flask related envs# Can be 'production' or 'development'FLASK_ENV=productiondiff --git a/unstract/core/src/unstract/core/cache/exceptions.py b/unstract/core/src/unstract/core/cache/exceptions.pynew file mode 100644index 000000000..2b31e5a20--- /dev/null+++ b/unstract/core/src/unstract/core/cache/exceptions.py@@ -0,0 +1,4 @@+class RedisSentinelConnectionError(ConnectionError):+ """Raised when Sentinel connection cannot be established after all retries."""++ passdiff --git a/unstract/core/src/unstract/core/cache/redis_client.py b/unstract/core/src/unstract/core/cache/redis_client.pyindex 12ababdba..b6b2fb20a 100644--- a/unstract/core/src/unstract/core/cache/redis_client.py+++ b/unstract/core/src/unstract/core/cache/redis_client.py@@ -1,16 +1,296 @@-"""Base Redis Client for Workers+"""Redis Client with Sentinel HA Support-Provides a comprehensive Redis client with all common Redis operations.-This serves as the foundation for specialized clients (queue, cache, etc.).+Dual-mode Redis configuration:+- Standalone mode: traditional redis.Redis() when REDIS_SENTINEL_MODE is absent/False+- Sentinel mode: Sentinel.master_for() when REDIS_SENTINEL_MODE=True++Mode is detected from {prefix}SENTINEL_MODE env var (LLMW pattern).+In Sentinel mode, REDIS_HOST/REDIS_PORT point to the K8s Sentinel service endpoint.+Master name defaults to "mymaster" (configurable via REDIS_SENTINEL_MASTER_NAME env var).+REDIS_PASSWORD is reused for Sentinel auth.++Retry: 10 attempts, 5s initial, 1.5x backoff, ±20% jitter."""import logging+import os+import random+import timefrom typing import Anyimport redis+from redis.sentinel import Sentinel++from unstract.core.cache.exceptions import RedisSentinelConnectionErrorlogger = logging.getLogger(__name__)+_SENTINEL_MAX_RETRIES = 10+_SENTINEL_INITIAL_DELAY = 5 # seconds+_SENTINEL_BACKOFF_MULTIPLIER = 1.5+_SENTINEL_JITTER_MIN = 0.8+_SENTINEL_JITTER_MAX = 1.2+_DEFAULT_SENTINEL_MASTER_NAME = os.getenv("REDIS_SENTINEL_MASTER_NAME", "mymaster")+++def _is_sentinel_mode(env_prefix: str) -> bool:+ return os.getenv(f"{env_prefix}SENTINEL_MODE", "False").strip().lower() == "true"+++def create_redis_client(+ env_prefix: str = "REDIS_",+ decode_responses: bool = True,+ socket_connect_timeout: int = 5,+ socket_timeout: int = 5,+ max_connections: int | None = None,+ health_check_interval: int = 0,+ db: int | None = None,+) -> redis.Redis:+ """Factory to create a Redis client in Standalone or Sentinel mode.++ Mode is detected from {env_prefix}SENTINEL_MODE env var.+ In Sentinel mode, {env_prefix}HOST and {env_prefix}PORT point to the+ Sentinel service endpoint (K8s DNS). Master name from+ {env_prefix}SENTINEL_MASTER_NAME env (falls back to REDIS_SENTINEL_MASTER_NAME).++ Args:+ env_prefix: Env var prefix (e.g. "REDIS_" or "CACHE_REDIS_").+ decode_responses: Whether to decode responses to strings.+ socket_connect_timeout: Connection timeout in seconds.+ socket_timeout: Socket timeout in seconds.+ max_connections: Optional max connections for ConnectionPool.+ health_check_interval: Proactive health check interval in seconds (0=disabled).+ db: Optional DB index override.++ Returns:+ Configured redis.Redis client (standalone or Sentinel-backed).++ Raises:+ RedisSentinelConnectionError: After exhausting retries in Sentinel mode.+ """+ if _is_sentinel_mode(env_prefix):+ return _create_sentinel_client(+ env_prefix=env_prefix,+ decode_responses=decode_responses,+ socket_connect_timeout=socket_connect_timeout,+ socket_timeout=socket_timeout,+ health_check_interval=health_check_interval,+ max_connections=max_connections,+ db_override=db,+ )+ else:+ return _create_standalone_client(+ env_prefix=env_prefix,+ decode_responses=decode_responses,+ socket_connect_timeout=socket_connect_timeout,+ socket_timeout=socket_timeout,+ max_connections=max_connections,+ health_check_interval=health_check_interval,+ db_override=db,+ )+++def _resolve_redis_env(+ env_prefix: str, default_port: str = "6379", db_override: int | None = None+) -> dict[str, Any]:+ """Read common Redis env vars into a dict."""+ host = os.getenv(f"{env_prefix}HOST", os.getenv("REDIS_HOST", "localhost"))+ port = int(os.getenv(f"{env_prefix}PORT", os.getenv("REDIS_PORT", default_port)))+ password = os.getenv(f"{env_prefix}PASSWORD", os.getenv("REDIS_PASSWORD"))+ username = os.getenv(+ f"{env_prefix}USER",+ os.getenv(f"{env_prefix}USERNAME", os.getenv("REDIS_USER")),+ )+ db = (+ db_override+ if db_override is not None+ else int(os.getenv(f"{env_prefix}DB", os.getenv("REDIS_DB", "0")))+ )+ return {+ "host": host,+ "port": port,+ "password": password,+ "username": username,+ "db": db,+ }+++def _build_connection_kwargs(+ env: dict[str, Any],+ decode_responses: bool,+ socket_connect_timeout: int,+ socket_timeout: int,+ health_check_interval: int = 0,+ max_connections: int | None = None,+ include_auth_only: bool = False,+) -> dict[str, Any]:+ """Build kwargs dict for Redis/Sentinel connections.++ Args:+ include_auth_only: If True, only include password/username (for sentinel_kwargs).+ """+ if include_auth_only:+ kwargs: dict[str, Any] = {+ "socket_connect_timeout": socket_connect_timeout,+ "socket_timeout": socket_timeout,+ }+ if env.get("password"):+ kwargs["password"] = env["password"]+ if env.get("username"):+ kwargs["username"] = env["username"]+ return kwargs++ kwargs = {+ "socket_connect_timeout": socket_connect_timeout,+ "socket_timeout": socket_timeout,+ "decode_responses": decode_responses,+ "db": env["db"],+ }+ if health_check_interval:+ kwargs["health_check_interval"] = health_check_interval+ if max_connections is not None:+ kwargs["max_connections"] = max_connections+ if env.get("password"):+ kwargs["password"] = env["password"]+ if env.get("username"):+ kwargs["username"] = env["username"]+ return kwargs+++def _create_standalone_client(+ env_prefix: str,+ decode_responses: bool,+ socket_connect_timeout: int,+ socket_timeout: int,+ max_connections: int | None,+ health_check_interval: int = 0,+ db_override: int | None = None,+) -> redis.Redis:+ env = _resolve_redis_env(env_prefix, default_port="6379", db_override=db_override)++ logger.info(+ "Redis standalone mode enabled. Connecting to %s:%s", env["host"], env["port"]+ )++ kwargs: dict[str, Any] = {+ "host": env["host"],+ "port": env["port"],+ "password": env["password"],+ "username": env["username"],+ "db": env["db"],+ "decode_responses": decode_responses,+ "socket_connect_timeout": socket_connect_timeout,+ "socket_timeout": socket_timeout,+ }+ if health_check_interval:+ kwargs["health_check_interval"] = health_check_interval++ if max_connections is not None:+ pool = redis.ConnectionPool(max_connections=max_connections, **kwargs)+ return redis.Redis(connection_pool=pool)++ return redis.Redis(**kwargs)+++def _create_sentinel_client(+ env_prefix: str,+ decode_responses: bool,+ socket_connect_timeout: int,+ socket_timeout: int,+ health_check_interval: int = 0,+ max_connections: int | None = None,+ db_override: int | None = None,+) -> redis.Redis:+ env = _resolve_redis_env(env_prefix, default_port="26379", db_override=db_override)+ master_name = os.getenv(+ f"{env_prefix}SENTINEL_MASTER_NAME", _DEFAULT_SENTINEL_MASTER_NAME+ )++ logger.info(+ "Redis Sentinel mode enabled. Connecting to sentinel at %s:%s, master: %s",+ env["host"],+ env["port"],+ master_name,+ )++ # When sentinel_kwargs is provided, redis-py does NOT inherit socket+ # timeouts from connection_kwargs, so we must include them explicitly+ sentinel_kwargs = _build_connection_kwargs(+ env,+ decode_responses,+ socket_connect_timeout,+ socket_timeout,+ include_auth_only=True,+ )+ master_kwargs = _build_connection_kwargs(+ env,+ decode_responses,+ socket_connect_timeout,+ socket_timeout,+ health_check_interval=health_check_interval,+ max_connections=max_connections,+ )++ return _connect_with_retry(env, master_name, sentinel_kwargs, master_kwargs)+++def _connect_with_retry(+ env: dict[str, Any],+ master_name: str,+ sentinel_kwargs: dict[str, Any],+ master_kwargs: dict[str, Any],+) -> redis.Redis:+ """Attempt Sentinel connection with exponential backoff retry."""+ host, port = env["host"], env["port"]+ last_error: Exception | None = None++ for attempt in range(_SENTINEL_MAX_RETRIES):+ try:+ sentinel = Sentinel(+ [(host, port)],+ socket_connect_timeout=sentinel_kwargs["socket_connect_timeout"],+ socket_timeout=sentinel_kwargs["socket_timeout"],+ sentinel_kwargs=sentinel_kwargs,+ )+ client = sentinel.master_for(master_name, **master_kwargs)+ client.ping()+ return client+ except (+ redis.exceptions.ConnectionError,+ redis.exceptions.TimeoutError,+ OSError,+ ) as e:+ last_error = e+ if attempt >= _SENTINEL_MAX_RETRIES - 1:+ break+ delay = (+ _SENTINEL_INITIAL_DELAY+ * (_SENTINEL_BACKOFF_MULTIPLIER**attempt)+ * random.uniform(_SENTINEL_JITTER_MIN, _SENTINEL_JITTER_MAX)+ )+ logger.warning(+ "Sentinel connection attempt %d/%d failed. Retrying in %.1fs. Error: %s",+ attempt + 1,+ _SENTINEL_MAX_RETRIES,+ delay,+ e,+ )+ time.sleep(delay)+ except Exception as e:+ raise RedisSentinelConnectionError(+ f"Non-retriable error connecting to Redis Sentinel: {e}"+ ) from e++ raise RedisSentinelConnectionError(+ f"Failed to connect to Redis Sentinel after {_SENTINEL_MAX_RETRIES} retries "+ f"(~5 minutes).\n"+ f"Sentinel endpoint: {host}:{port}\n"+ f"Service: {master_name}\n"+ f"Check Sentinel availability, REDIS_HOST, REDIS_PORT, and "+ f"REDIS_SENTINEL_MODE configuration.\n"+ f"Last error: {last_error}"+ )+class RedisClient:"""Base Redis client with comprehensive operations."""@@ -26,18 +306,6 @@ class RedisClient:socket_connect_timeout: int = 5,socket_timeout: int = 5,):- """Initialize Redis client.-- Args:- host: Redis host- port: Redis port- username: Redis username (optional)- password: Redis password (optional)- db: Redis database number- decode_responses: Whether to decode responses to strings- socket_connect_timeout: Connection timeout in seconds- socket_timeout: Socket timeout in seconds- """self.redis_client = redis.Redis(host=host,port=port,@@ -51,14 +319,6 @@ class RedisClient:# Basic key-value operationsdef get(self, key: str) -> Any:- """Get value by key.-- Args:- key: Redis key-- Returns:- Value or None if key doesn't exist- """return self.redis_client.get(key)def set(@@ -70,162 +330,52 @@ class RedisClient:nx: bool = False,xx: bool = False,) -> bool:- """Set key to value.-- Args:- key: Redis key- value: Value to set- ex: Expire time in seconds- px: Expire time in milliseconds- nx: Only set if key doesn't exist- xx: Only set if key exists-- Returns:- True if set successfully- """return self.redis_client.set(key, value, ex=ex, px=px, nx=nx, xx=xx)def setex(self, key: str, time: int, value: Any) -> bool:- """Set key with expiration time.-- Args:- key: Redis key- time: Expiration time in seconds- value: Value to set-- Returns:- True if set successfully- """return self.redis_client.setex(key, time, value)def delete(self, *keys: str) -> int:- """Delete one or more keys.-- Args:- *keys: Keys to delete-- Returns:- Number of keys deleted- """return self.redis_client.delete(*keys)def exists(self, *keys: str) -> int:- """Check if keys exist.-- Args:- *keys: Keys to check-- Returns:- Number of keys that exist- """return self.redis_client.exists(*keys)# TTL operationsdef expire(self, key: str, time: int) -> bool:- """Set expiration time on key.-- Args:- key: Redis key- time: Expiration time in seconds-- Returns:- True if timeout was set- """return self.redis_client.expire(key, time)def ttl(self, key: str) -> int:- """Get time to live for key.-- Args:- key: Redis key-- Returns:- TTL in seconds, -1 if no expiry, -2 if key doesn't exist- """return self.redis_client.ttl(key)def persist(self, key: str) -> bool:- """Remove expiration from key.-- Args:- key: Redis key-- Returns:- True if expiration was removed- """return self.redis_client.persist(key)# Batch operationsdef mget(self, keys: list[str]) -> list[Any]:- """Get multiple values at once.-- Args:- keys: List of Redis keys-- Returns:- List of values (None for non-existent keys)- """return self.redis_client.mget(keys)def mset(self, mapping: dict[str, Any]) -> bool:- """Set multiple key-value pairs at once.-- Args:- mapping: Dictionary of key-value pairs-- Returns:- True if all keys were set- """return self.redis_client.mset(mapping)# Key scanning and patternsdef keys(self, pattern: str = "*") -> list[str]:- """Get all keys matching pattern.-- Warning: Use scan() for production - keys() blocks the server.-- Args:- pattern: Key pattern (supports wildcards)-- Returns:- List of matching keys- """return self.redis_client.keys(pattern)def scan(self, cursor: int = 0, match: str | None = None, count: int | None = None) -> tuple[int, list[str]]:- """Incrementally iterate over keys (non-blocking).-- Args:- cursor: Cursor position (0 to start)- match: Key pattern to match- count: Approximate number of keys to return-- Returns:- Tuple of (next_cursor, list_of_keys)- """return self.redis_client.scan(cursor=cursor, match=match, count=count)+ def incr(self, key: str) -> int:+ return self.redis_client.incr(key)+# Pipeline supportdef pipeline(self, transaction: bool = True) -> redis.client.Pipeline:- """Create a pipeline for batching commands.-- Args:- transaction: Whether to use MULTI/EXEC transaction-- Returns:- Redis pipeline object- """return self.redis_client.pipeline(transaction=transaction)# Health checkdef ping(self) -> bool:- """Check Redis connectivity.-- Returns:- True if connected, False otherwise- """try:self.redis_client.ping()return True@@ -234,37 +384,35 @@ class RedisClient:# Connection infodef info(self, section: str | None = None) -> dict[str, Any]:- """Get Redis server information.-- Args:- section: Specific info section (e.g., 'memory', 'stats')-- Returns:- Dictionary of server information- """return self.redis_client.info(section=section)@classmethod- def from_env(cls) -> "RedisClient":- """Create client from environment variables.-- Environment variables:- REDIS_HOST: Redis host (default: localhost)- REDIS_PORT: Redis port (default: 6379)- REDIS_USER: Redis username (optional)- REDIS_USERNAME: Redis username (optional, alternative to REDIS_USER)- REDIS_PASSWORD: Redis password (optional)- REDIS_DB: Redis database number (default: 0)-- Returns:- Configured RedisClient instance+ def from_env(cls, env_prefix: str = "REDIS_") -> "RedisClient":+ """Create client from environment variables, with Sentinel support.++ When {env_prefix}SENTINEL_MODE is True, returns a RedisClient backed+ by a Sentinel-managed connection. Otherwise uses standalone mode."""- import os-- return cls(- host=os.getenv("REDIS_HOST", "localhost"),- port=int(os.getenv("REDIS_PORT", "6379")),- username=os.getenv("REDIS_USER") or os.getenv("REDIS_USERNAME"),- password=os.getenv("REDIS_PASSWORD"),- db=int(os.getenv("REDIS_DB", "0")),- )+ if _is_sentinel_mode(env_prefix):+ instance = cls.__new__(cls)+ instance.redis_client = create_redis_client(+ env_prefix=env_prefix, decode_responses=True+ )+ return instance+ else:+ host = os.getenv(f"{env_prefix}HOST", os.getenv("REDIS_HOST", "localhost"))+ port = int(os.getenv(f"{env_prefix}PORT", os.getenv("REDIS_PORT", "6379")))+ username = os.getenv(+ f"{env_prefix}USER",+ os.getenv(f"{env_prefix}USERNAME", os.getenv("REDIS_USER")),+ )+ password = os.getenv(f"{env_prefix}PASSWORD", os.getenv("REDIS_PASSWORD"))+ db = int(os.getenv(f"{env_prefix}DB", os.getenv("REDIS_DB", "0")))++ return cls(+ host=host,+ port=port,+ username=username,+ password=password,+ db=db,+ )diff --git a/unstract/core/src/unstract/core/file_execution_tracker.py b/unstract/core/src/unstract/core/file_execution_tracker.pyindex 43c5fabe3..e476c6252 100644--- a/unstract/core/src/unstract/core/file_execution_tracker.py+++ b/unstract/core/src/unstract/core/file_execution_tracker.py@@ -5,8 +5,7 @@ from dataclasses import asdict, dataclassfrom enum import Enumfrom typing import Any-import redis-+from unstract.core.cache.redis_client import create_redis_clientfrom unstract.core.exceptions import (FileExecutionStageException,FileExecutionTrackerNotFound,@@ -156,14 +155,17 @@ class FileExecutionStatusTracker:os.environ.get("FILE_EXECUTION_TRACKER_TTL_IN_SECOND", 60 * 60 * 24))+ # Lazy singleton — avoids per-instance Sentinel discovery + retry overhead+ _redis_client = None++ @classmethod+ def _get_redis_client(cls):+ if cls._redis_client is None:+ cls._redis_client = create_redis_client(decode_responses=True)+ return cls._redis_client+def __init__(self):- self.redis_client = redis.Redis(- host=os.environ.get("REDIS_HOST"),- port=int(os.environ.get("REDIS_PORT", 6379)),- username=os.environ.get("REDIS_USER"),- password=os.environ.get("REDIS_PASSWORD"),- decode_responses=True, # ensures hgetall returns str instead of bytes- )+ self.redis_client = self._get_redis_client()def _resolve_field(self,diff --git a/unstract/core/src/unstract/core/log_utils.py b/unstract/core/src/unstract/core/log_utils.pyindex 718f559aa..824991a3f 100644--- a/unstract/core/src/unstract/core/log_utils.py+++ b/unstract/core/src/unstract/core/log_utils.py@@ -116,32 +116,3 @@ def store_execution_log(except Exception as e:logger.error(f"Error storing execution log: {e}")---def create_redis_client(- host: str = "localhost",- port: int = 6379,- username: str | None = None,- password: str | None = None,- **kwargs,-) -> redis.Redis:- """Create Redis client with configuration.-- Args:- host: Redis host- port: Redis port- username: Redis username (optional)- password: Redis password (optional)- **kwargs: Additional Redis configuration-- Returns:- Configured Redis client- """- return redis.Redis(- host=host,- port=port,- username=username,- password=password,- decode_responses=False, # Keep as bytes for consistency- **kwargs,- )diff --git a/unstract/core/src/unstract/core/pubsub_helper.py b/unstract/core/src/unstract/core/pubsub_helper.pyindex 6f96d9f7c..5f89f5c7c 100644--- a/unstract/core/src/unstract/core/pubsub_helper.py+++ b/unstract/core/src/unstract/core/pubsub_helper.py@@ -7,9 +7,9 @@ from datetime import UTC, datetimefrom typing import Anyimport httpx-import redisfrom kombu import Connection+from unstract.core.cache.redis_client import create_redis_clientfrom unstract.core.constants import LogEventArgument, LogProcessingTask@@ -21,12 +21,13 @@ class LogPublisher:))kombu_conn = Connection(broker_url)- r = redis.Redis(- host=os.environ.get("REDIS_HOST"),- port=os.environ.get("REDIS_PORT", 6379),- username=os.environ.get("REDIS_USER"),- password=os.environ.get("REDIS_PASSWORD"),- )+ _redis_client: Any = None++ @classmethod+ def _get_redis_client(cls) -> Any:+ if cls._redis_client is None:+ cls._redis_client = create_redis_client(decode_responses=False)+ return cls._redis_client@staticmethoddef log_usage(@@ -183,7 +184,7 @@ class LogPublisher:timestamp = payload.get("timestamp", round(time.time(), 6))redis_key = f"{event}:{timestamp}"log_data = json.dumps(payload)- cls.r.setex(redis_key, logs_expiration, log_data)+ cls._get_redis_client().setex(redis_key, logs_expiration, log_data)except Exception as e:logging.error(f"Failed to store unified notification log for '{event}' "diff --git a/unstract/core/src/unstract/core/tool_execution_status.py b/unstract/core/src/unstract/core/tool_execution_status.pyindex ca56180bc..4dd11a348 100644--- a/unstract/core/src/unstract/core/tool_execution_status.py+++ b/unstract/core/src/unstract/core/tool_execution_status.py@@ -3,8 +3,7 @@ import osfrom dataclasses import dataclassfrom enum import Enum-import redis-+from unstract.core.cache.redis_client import create_redis_clientfrom unstract.core.exceptions import (ToolExecutionStatusException,ToolExecutionValueException,@@ -62,14 +61,17 @@ class ToolExecutionTracker:))+ # Lazy singleton — avoids per-instance Sentinel discovery + retry overhead+ _redis_client = None++ @classmethod+ def _get_redis_client(cls):+ if cls._redis_client is None:+ cls._redis_client = create_redis_client(decode_responses=True)+ return cls._redis_client+def __init__(self):- self.redis_client = redis.Redis(- host=os.environ.get("REDIS_HOST"),- port=int(os.environ.get("REDIS_PORT", 6379)),- username=os.environ.get("REDIS_USER"),- password=os.environ.get("REDIS_PASSWORD"),- decode_responses=True, # ensures hgetall returns str instead of bytes- )+ self.redis_client = self._get_redis_client()def _resolve_field(self,diff --git a/unstract/workflow-execution/src/unstract/workflow_execution/api_deployment/cache_utils.py b/unstract/workflow-execution/src/unstract/workflow_execution/api_deployment/cache_utils.pyindex 85b9a7ad4..bc882ae6a 100644--- a/unstract/workflow-execution/src/unstract/workflow_execution/api_deployment/cache_utils.py+++ b/unstract/workflow-execution/src/unstract/workflow_execution/api_deployment/cache_utils.py@@ -5,8 +5,7 @@ import loggingimport osfrom typing import Any-import redis-+from unstract.core.cache.redis_client import create_redis_clientfrom unstract.core.worker_models import FileExecutionResultlogger = logging.getLogger(__name__)@@ -24,19 +23,11 @@ class WorkerResultCacheUtils:def _get_redis_client(self):"""Get Redis client instance."""if self._redis_client is None:- host = os.getenv("REDIS_HOST", "localhost")- port = int(os.getenv("REDIS_PORT", "6379"))- db = int(os.getenv("REDIS_DB", "0"))-- self._redis_client = redis.Redis(- host=host,- port=port,- db=db,- decode_responses=False, # Keep binary for JSON handling+ self._redis_client = create_redis_client(+ decode_responses=False,socket_connect_timeout=5,socket_timeout=5,)-return self._redis_clientdef check_redis_health(self, timeout_seconds: float = 2.0) -> bool:diff --git a/unstract/workflow-execution/src/unstract/workflow_execution/workflow_execution.py b/unstract/workflow-execution/src/unstract/workflow_execution/workflow_execution.pyindex 0a15a7c72..ffd5ff27c 100644--- a/unstract/workflow-execution/src/unstract/workflow_execution/workflow_execution.py+++ b/unstract/workflow-execution/src/unstract/workflow_execution/workflow_execution.py@@ -1,10 +1,8 @@import logging-import osimport timefrom typing import Any-import redis-+from unstract.core.cache.redis_client import create_redis_clientfrom unstract.core.pubsub_helper import LogPublisherfrom unstract.tool_sandbox import ToolSandboxfrom unstract.workflow_execution.constants import StepExecution, ToolExecution@@ -29,12 +27,13 @@ logger = logging.getLogger(__name__)class WorkflowExecutionService:- redis_con = redis.Redis(- host=os.environ.get("REDIS_HOST", "http://127.0.0.1"),- port=int(os.environ.get("REDIS_PORT", "6379")),- password=os.environ.get("REDIS_USER"),- username=os.environ.get("REDIS_PASSWORD"),- )+ _redis_client = None++ @classmethod+ def _get_redis_client(cls):+ if cls._redis_client is None:+ cls._redis_client = create_redis_client(decode_responses=False)+ return cls._redis_clientdef __init__(self,@@ -48,6 +47,7 @@ class WorkflowExecutionService:) -> None:self.organization_id = organization_idself.workflow_id = workflow_id+ self.redis_con = self._get_redis_client()self.tool_instances = tool_instancesself.tool_utils = ToolsUtils(diff --git a/workers/log_consumer/tasks.py b/workers/log_consumer/tasks.pyindex eeae05f47..56af72592 100644--- a/workers/log_consumer/tasks.py+++ b/workers/log_consumer/tasks.py@@ -5,6 +5,7 @@ This module contains Celery tasks for processing execution logs.import osfrom typing import Any+from urllib.parse import quoteimport socketiofrom celery import shared_task@@ -29,15 +30,37 @@ log_queue_name = os.getenv("LOG_HISTORY_QUEUE_NAME", "log_history_queue")log_storage_enabled = os.getenv("ENABLE_LOG_HISTORY", "true").lower() == "true"# Socket.IO client for emitting events (uses same KombuManager as backend)-redis_host = os.getenv("REDIS_HOST", "localhost")-redis_port = os.getenv("REDIS_PORT", "6379")-socket_io_manager_url = f"redis://{redis_host}:{redis_port}"+_sentinel_mode = os.getenv("REDIS_SENTINEL_MODE", "False").strip().lower() == "true"+_redis_host = os.getenv("REDIS_HOST", "localhost")+_redis_port = os.getenv("REDIS_PORT", "6379")+_redis_password = os.getenv("REDIS_PASSWORD", "")+_redis_user = os.getenv("REDIS_USER", "")+_cred_prefix = ""+if _redis_user and _redis_password:+ _cred_prefix = f"{quote(_redis_user, safe='')}:{quote(_redis_password, safe='')}@"+elif _redis_password:+ _cred_prefix = f":{quote(_redis_password, safe='')}@"++_transport_options: dict[str, Any] = {}+if _sentinel_mode:+ _redis_db = os.getenv("REDIS_DB", "0") or "0"+ socket_io_manager_url = (+ f"sentinel://{_cred_prefix}{_redis_host}:{_redis_port}/{_redis_db}"+ )+ _sentinel_master_name = os.getenv("REDIS_SENTINEL_MASTER_NAME", "mymaster")+ _transport_options = {"master_name": _sentinel_master_name}+else:+ socket_io_manager_url = f"redis://{_cred_prefix}{_redis_host}:{_redis_port}"sio = socketio.Server(async_mode="threading",logger=False,engineio_logger=False,- client_manager=socketio.KombuManager(url=socket_io_manager_url, write_only=True),+ client_manager=socketio.KombuManager(+ url=socket_io_manager_url,+ write_only=True,+ **({"transport_options": _transport_options} if _transport_options else {}),+ ),)diff --git a/workers/sample.env b/workers/sample.envindex 516fc242e..a2c10a338 100644--- a/workers/sample.env+++ b/workers/sample.env@@ -72,6 +72,12 @@ REDIS_PASSWORD=REDIS_USER=defaultREDIS_DB=0+# Redis Sentinel mode for SocketIO log consumer+# When True: point REDIS_HOST to Sentinel K8s service DNS, REDIS_PORT to 26379+# REDIS_PASSWORD is reused for Sentinel auth.+REDIS_SENTINEL_MODE=False+REDIS_SENTINEL_MASTER_NAME=mymaster+# Cache-Specific Redis ConfigurationCACHE_REDIS_ENABLED=trueCACHE_REDIS_HOST=unstract-redis@@ -82,6 +88,10 @@ CACHE_REDIS_USERNAME=CACHE_REDIS_SSL=falseCACHE_REDIS_SSL_CERT_REQS=required+# Cache Redis Sentinel mode for worker execution cache backend+# When True: point CACHE_REDIS_HOST to Sentinel K8s service DNS, CACHE_REDIS_PORT to 26379+CACHE_REDIS_SENTINEL_MODE=False+# Database URL (for fallback usage)DATABASE_URL=postgresql://unstract_dev:unstract_pass@unstract-db:5432/unstract_dbdiff --git a/workers/shared/cache/cache_backends.py b/workers/shared/cache/cache_backends.pyindex 24363801a..84c0297be 100644--- a/workers/shared/cache/cache_backends.py+++ b/workers/shared/cache/cache_backends.py@@ -7,11 +7,12 @@ This module provides abstract and concrete cache backend implementations:import jsonimport logging+import osfrom abc import ABC, abstractmethodfrom datetime import UTC, datetimefrom typing import Any-from unstract.core.cache.redis_client import RedisClient+from unstract.core.cache.redis_client import RedisClient, create_redis_clientlogger = logging.getLogger(__name__)@@ -99,17 +100,34 @@ class RedisCacheBackend(BaseCacheBackend):self.available = Falsereturn- # Initialize RedisClient with cache configuration- self.redis_client = RedisClient(- host=cache_config["host"],- port=cache_config["port"],- username=cache_config.get("username"),- password=cache_config.get("password"),- db=cache_config["db"],- decode_responses=True,- socket_timeout=5,- socket_connect_timeout=5,+ # Check for Sentinel mode via CACHE_REDIS_SENTINEL_MODE+ sentinel_mode = (+ os.getenv("CACHE_REDIS_SENTINEL_MODE", "False").strip().lower() == "true")+ if sentinel_mode:+ # Sentinel mode: use factory with CACHE_REDIS_ prefix+ raw_client = create_redis_client(+ env_prefix="CACHE_REDIS_",+ decode_responses=True,+ socket_timeout=5,+ socket_connect_timeout=5,+ health_check_interval=30,+ )+ # Wrap in RedisClient for interface compatibility+ self.redis_client = RedisClient.__new__(RedisClient)+ self.redis_client.redis_client = raw_client+ else:+ # Standalone mode: use RedisClient directly+ self.redis_client = RedisClient(+ host=cache_config["host"],+ port=cache_config["port"],+ username=cache_config.get("username"),+ password=cache_config.get("password"),+ db=cache_config["db"],+ decode_responses=True,+ socket_timeout=5,+ socket_connect_timeout=5,+ )# Test connectionif not self.redis_client.ping():@@ -117,7 +135,8 @@ class RedisCacheBackend(BaseCacheBackend):self.available = Truelogger.info(- f"RedisCacheBackend initialized successfully: {cache_config['host']}:{cache_config['port']}/{cache_config['db']}"+ f"RedisCacheBackend initialized successfully: "+ f"{cache_config['host']}:{cache_config['port']}/{cache_config['db']}")except ImportError:diff --git a/workers/shared/infrastructure/caching/cache_utils.py b/workers/shared/infrastructure/caching/cache_utils.pyindex 3d85db4d3..69f7f0109 100644--- a/workers/shared/infrastructure/caching/cache_utils.py+++ b/workers/shared/infrastructure/caching/cache_utils.py@@ -6,11 +6,14 @@ Specifically optimized for callback pattern performance optimizations.import jsonimport logging+import osimport timeimport redisfrom shared.infrastructure.config import WorkerConfig+from unstract.core.cache.redis_client import create_redis_client+logger = logging.getLogger(__name__)@@ -39,34 +42,42 @@ class WorkerCacheManager:logger.info("Redis cache disabled via configuration")return- # Use direct cache Redis configuration (not Celery broker)- redis_kwargs = {- "host": cache_config["host"],- "port": cache_config["port"],- "db": cache_config["db"],- "decode_responses": True,- "socket_connect_timeout": 5,- "socket_timeout": 5,- "health_check_interval": 30,- }-- # Add authentication if configured- if cache_config.get("password"):- redis_kwargs["password"] = cache_config["password"]- if cache_config.get("username"):- redis_kwargs["username"] = cache_config["username"]-- # Add SSL configuration if enabled- if cache_config.get("ssl"):- redis_kwargs["ssl"] = True- redis_kwargs["ssl_cert_reqs"] = self.config.cache_redis_ssl_cert_reqs-- self._redis_client = redis.Redis(**redis_kwargs)+ # Check for Sentinel mode+ sentinel_mode = (+ os.getenv("CACHE_REDIS_SENTINEL_MODE", "False").strip().lower() == "true"+ )+ if sentinel_mode:+ # Sentinel mode: use factory with CACHE_REDIS_ prefix+ self._redis_client = create_redis_client(+ env_prefix="CACHE_REDIS_",+ decode_responses=True,+ socket_timeout=5,+ socket_connect_timeout=5,+ health_check_interval=30,+ )+ else:+ # Standalone mode+ redis_kwargs = {+ "host": cache_config["host"],+ "port": cache_config["port"],+ "db": cache_config["db"],+ "decode_responses": True,+ "socket_connect_timeout": 5,+ "socket_timeout": 5,+ "health_check_interval": 30,+ }+ if cache_config.get("password"):+ redis_kwargs["password"] = cache_config["password"]+ if cache_config.get("username"):+ redis_kwargs["username"] = cache_config["username"]+ if cache_config.get("ssl"):+ redis_kwargs["ssl"] = True+ redis_kwargs["ssl_cert_reqs"] = self.config.cache_redis_ssl_cert_reqs+ self._redis_client = redis.Redis(**redis_kwargs)# Test connectionself._redis_client.ping()self._last_connection_time = time.time()- # Create unique connection ID to detect reconnectionsself._connection_id = f"cache_conn_{int(self._last_connection_time)}"logger.info(f"Redis cache initialized: {cache_config['host']}:{cache_config['port']}/{cache_config['db']}"