Performance: Redis as message broker
This affects the responsiveness and throughput of message passing between components in a web application.
import redis from flask import Flask app = Flask(__name__) r = redis.Redis() @app.route('/send/<msg>') def send(msg): r.lpush('messages', msg) return 'Message sent' @app.route('/receive') def receive(): msg = r.rpop('messages') return msg.decode() if msg else 'No messages'
from flask import Flask app = Flask(__name__) messages = [] @app.route('/send/<msg>') def send(msg): messages.append(msg) return 'Message sent' @app.route('/receive') def receive(): if messages: return messages.pop(0) return 'No messages'
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| In-memory message queue in Flask | None | Blocks main thread | Delays response rendering | [X] Bad |
| Redis message broker with Flask | None | Non-blocking | Fast response rendering | [OK] Good |
publish to send messages to a channel.publish is the correct Redis command; others like send, push, or post are incorrect.import redis
r = redis.Redis()
pubsub = r.pubsub()
pubsub.subscribe('test_channel')
for message in pubsub.listen():
if message['type'] == 'message':
print(message['data'].decode())
break
import redis
r = redis.Redis()
pubsub = r.pubsub()
pubsub.subscribe('channel')
for message in pubsub.listen():
if message['type'] == 'message':
print(message['data'].decode())
It causes the Flask app to freeze and not respond.Pass the test and this pattern moves unknown