Spaces:
Paused

dushyantsingh0 Claude Sonnet 4.6 commited on
Commit
5df217f
Β·
1 Parent(s): b34dce7

fix: use local Redis for WebSocket pub/sub, not Upstash

Browse files

The previous approach (polling get_message every 100ms across 4 workers)
would have consumed ~3.5M Upstash commands/day β€” far beyond any free tier.

Root cause was using CACHE_REDIS_URL (Upstash) for pub/sub. Upstash is a
serverless/HTTP Redis designed for short request-response operations. It
imposes a 30-second idle-connection timeout and bills per command, making
it fundamentally unsuitable for a persistent pub/sub listener.

Fix: route WebSocket pub/sub through LOCAL_REDIS_URL (localhost:6379).
The local Redis is already started by run_prod.sh and all 4 Gunicorn
workers share the same host, so local pub/sub fan-out works correctly.
Zero Upstash commands consumed. No idle timeouts. No polling hacks needed.

Changes:
- main.py: pass settings.LOCAL_REDIS_URL to ws_manager.start_pubsub()
instead of settings.clean_cache_redis_url
- core/websockets.py: revert subscriber to clean listen() loop (no polling,
no keepalive PING), simplify _get_pub_redis() to use local URL directly

Note: if deploying across multiple physical servers in future, point
LOCAL_REDIS_URL at a shared Redis that all servers can reach.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

Files changed (2) hide show
  1. core/websockets.py +25 -53
  2. main.py +9 -3
core/websockets.py CHANGED
@@ -91,24 +91,22 @@ class ConnectionManager:
91
  # ── Internal: publish ─────────────────────────────────────────────────── #
92
 
93
  async def _get_pub_redis(self):
94
- """Lazy-initialise a dedicated async Redis client for publishing."""
 
 
 
 
95
  if self._pub_redis is None:
96
  import redis.asyncio as aioredis
97
  url = self._redis_url or "redis://localhost:6379"
98
- # Mirror SSL handling from core/cache.py
99
- if url.startswith("redis://") and any(
100
- h in url for h in ["redislabs.com", "upstash.io", ".com:"]
101
- ):
102
- url = url.replace("redis://", "rediss://", 1)
103
- kwargs: dict = {
104
- "encoding": "utf-8",
105
- "decode_responses": True,
106
- "socket_connect_timeout": 5.0,
107
- "socket_timeout": 5.0,
108
- }
109
- if url.startswith("rediss://"):
110
- kwargs["ssl_cert_reqs"] = None
111
- self._pub_redis = aioredis.from_url(url, **kwargs)
112
  return self._pub_redis
113
 
114
  async def _publish(self, channel: str, message: Any) -> bool:
@@ -133,61 +131,35 @@ class ConnectionManager:
133
  _dispatch_local() for every received message so this process's
134
  WebSocket connections receive cross-process broadcasts.
135
 
136
- Uses get_message() polling instead of listen() so we can send a
137
- keepalive PING every 20 s. This prevents Upstash (and any other
138
- serverless Redis provider) from closing idle pub/sub connections at
139
- their 30-second server-side timeout.
140
  """
141
  import redis.asyncio as aioredis
142
 
143
- url = redis_url
144
- if url.startswith("redis://") and any(
145
- h in url for h in ["redislabs.com", "upstash.io", ".com:"]
146
- ):
147
- url = url.replace("redis://", "rediss://", 1)
148
-
149
  kwargs: dict = {
150
  "encoding": "utf-8",
151
  "decode_responses": True,
152
  "socket_connect_timeout": 5.0,
153
- # No socket_timeout here β€” the 100 ms get_message() poll handles
154
- # responsiveness; we don't want a hard socket timeout that fires
155
- # before our 20 s keepalive PING can prevent it.
156
  }
157
- if url.startswith("rediss://"):
158
- kwargs["ssl_cert_reqs"] = None
159
-
160
- _PING_INTERVAL = 20.0 # must be < Upstash's 30 s idle-close threshold
161
 
162
  while True:
163
  sub_redis = None
164
  try:
165
- sub_redis = aioredis.from_url(url, **kwargs)
166
  pubsub = sub_redis.pubsub()
167
  await pubsub.psubscribe(_PATTERN)
168
  logger.info("WebSocket subscriber: listening on nexus:ws:*")
169
 
170
- last_ping = asyncio.get_event_loop().time()
171
-
172
- while True:
173
- # Poll for up to 100 ms; returns None when no message arrives.
174
- message = await pubsub.get_message(
175
- ignore_subscribe_messages=True,
176
- timeout=0.1,
177
  )
178
-
179
- if message and message.get("type") == "pmessage":
180
- await self._dispatch_local(
181
- channel=message["channel"],
182
- payload=message["data"],
183
- )
184
-
185
- # Keepalive: PING before Upstash drops the idle connection.
186
- now = asyncio.get_event_loop().time()
187
- if now - last_ping >= _PING_INTERVAL:
188
- await pubsub.ping()
189
- last_ping = now
190
-
191
  except asyncio.CancelledError:
192
  logger.info("WebSocket pub/sub subscriber cancelled.")
193
  break
 
91
  # ── Internal: publish ─────────────────────────────────────────────────── #
92
 
93
  async def _get_pub_redis(self):
94
+ """
95
+ Lazy-initialise a dedicated async Redis client for publishing.
96
+ Uses the same local Redis URL as the subscriber so both publish and
97
+ subscribe traffic stays off cloud/billed Redis instances.
98
+ """
99
  if self._pub_redis is None:
100
  import redis.asyncio as aioredis
101
  url = self._redis_url or "redis://localhost:6379"
102
+ self._pub_redis = aioredis.from_url(
103
+ url,
104
+ encoding="utf-8",
105
+ decode_responses=True,
106
+ socket_connect_timeout=5.0,
107
+ socket_timeout=5.0,
108
+ socket_keepalive=True,
109
+ )
 
 
 
 
 
 
110
  return self._pub_redis
111
 
112
  async def _publish(self, channel: str, message: Any) -> bool:
 
131
  _dispatch_local() for every received message so this process's
132
  WebSocket connections receive cross-process broadcasts.
133
 
134
+ IMPORTANT: redis_url must point at the LOCAL Redis, not a cloud/serverless
135
+ Redis (e.g. Upstash). Cloud providers impose idle-connection timeouts and
136
+ bill per command β€” both incompatible with a persistent pub/sub listener.
137
+ The local Redis (started by run_prod.sh) has no such limits.
138
  """
139
  import redis.asyncio as aioredis
140
 
 
 
 
 
 
 
141
  kwargs: dict = {
142
  "encoding": "utf-8",
143
  "decode_responses": True,
144
  "socket_connect_timeout": 5.0,
145
+ "socket_keepalive": True,
 
 
146
  }
 
 
 
 
147
 
148
  while True:
149
  sub_redis = None
150
  try:
151
+ sub_redis = aioredis.from_url(redis_url, **kwargs)
152
  pubsub = sub_redis.pubsub()
153
  await pubsub.psubscribe(_PATTERN)
154
  logger.info("WebSocket subscriber: listening on nexus:ws:*")
155
 
156
+ async for message in pubsub.listen():
157
+ if message["type"] != "pmessage":
158
+ continue
159
+ await self._dispatch_local(
160
+ channel=message["channel"],
161
+ payload=message["data"],
 
162
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
163
  except asyncio.CancelledError:
164
  logger.info("WebSocket pub/sub subscriber cancelled.")
165
  break
main.py CHANGED
@@ -52,10 +52,16 @@ async def lifespan(app: FastAPI):
52
  await get_nexus_app(is_agent=False)
53
 
54
  # 5. Start WebSocket Redis pub/sub subscriber.
55
- # Each worker process runs its own subscriber so cross-process broadcasts
56
- # (e.g. ticket update on worker A β†’ client connected to worker B) work correctly.
 
 
 
 
 
 
57
  from core.websockets import manager as ws_manager
58
- _ws_redis_url = settings.clean_cache_redis_url
59
  await ws_manager.start_pubsub(_ws_redis_url)
60
  logger.info("GLOBAL: WebSocket Redis pub/sub subscriber started.")
61
 
 
52
  await get_nexus_app(is_agent=False)
53
 
54
  # 5. Start WebSocket Redis pub/sub subscriber.
55
+ # Uses the LOCAL Redis (localhost:6379) β€” NOT the cloud/Upstash instance.
56
+ # Reason: pub/sub requires a persistent long-lived TCP connection. Cloud
57
+ # providers like Upstash impose 30-second idle timeouts and bill per command,
58
+ # making them unsuitable for always-on pub/sub. The local Redis (started by
59
+ # run_prod.sh before this process) has no such limits and costs nothing.
60
+ # All 4 Gunicorn workers share the same host, so localhost fan-out works
61
+ # correctly. If you ever move to multiple physical servers, point
62
+ # LOCAL_REDIS_URL at a shared Redis that all servers can reach.
63
  from core.websockets import manager as ws_manager
64
+ _ws_redis_url = settings.LOCAL_REDIS_URL
65
  await ws_manager.start_pubsub(_ws_redis_url)
66
  logger.info("GLOBAL: WebSocket Redis pub/sub subscriber started.")
67