0
0
Flaskframework~8 mins

Redis as message broker in Flask - Performance & Optimization

Choose your learning style9 modes available
Performance: Redis as message broker
MEDIUM IMPACT
This affects the responsiveness and throughput of message passing between components in a web application.
Passing messages between Flask app components asynchronously
Flask
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'
Offloads message storage and retrieval to Redis, enabling non-blocking, fast message passing.
📈 Performance GainNon-blocking IO; reduces main thread load; supports high concurrency
Passing messages between Flask app components asynchronously
Flask
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'
Storing messages in a list in memory blocks the main thread and does not scale well under load.
📉 Performance CostBlocks rendering for each message; causes slow response under concurrent requests
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
In-memory message queue in FlaskNoneBlocks main threadDelays response rendering[X] Bad
Redis message broker with FlaskNoneNon-blockingFast response rendering[OK] Good
Rendering Pipeline
Using Redis as a message broker moves message handling outside the Flask app process, reducing blocking during request handling.
Interaction Handling
Network IO
JavaScript Event Loop
⚠️ BottleneckInteraction Handling when using in-memory message queues
Core Web Vital Affected
INP
This affects the responsiveness and throughput of message passing between components in a web application.
Optimization Tips
1Use Redis to handle message queues outside the Flask main thread.
2Avoid in-memory message queues that block request handling.
3Monitor interaction responsiveness (INP) when implementing message brokers.
Performance Quiz - 3 Questions
Test your performance knowledge
What is a key performance benefit of using Redis as a message broker in a Flask app?
AIt increases the size of the Flask app bundle.
BIt offloads message handling from the main thread, reducing blocking.
CIt causes more DOM reflows during message passing.
DIt delays the first contentful paint.
DevTools: Performance
How to check: Record a session sending and receiving messages; observe main thread activity and request durations.
What to look for: Look for reduced main thread blocking and faster request completion times with Redis.