The Analogy: The Pre-Blast Warning Protocol at a Quarry
At a working quarry, no charge is ever detonated without a warning protocol. Minutes before a blast, the shot-firer sounds a long note on the site siren. The siren is not aimed at any one person; it simply announces, to the whole site, that a detonation is imminent. The shot-firer does not walk the quarry knocking on cabin doors, and does not keep a mental list of who is on shift today. They perform one action -- sound the warning -- and trust that everyone who needs to know will hear it and do their part.
What makes the protocol work is that the responders register themselves. The haul-truck drivers have standing orders to pull back to the muster point when the siren sounds; the perimeter spotter walks the exclusion zone and reports it clear; the site office stamps the time of the shot in the blast log; the gate crew closes the access road. None of these parties was named by the shot-firer. Each one, at the start of its shift, effectively signed onto the blast-response roster, and the siren is simply the event they all wait for. A new responsibility can be added to the roster -- a fresh environmental monitor, say -- without the shot-firer changing anything about how they sound the siren.
Crucially, this protocol is synchronous and blocking by design. The blast does not go ahead the instant the siren sounds; it goes ahead only once every registered responder has confirmed its part -- road closed, zone clear, log stamped. The shot-firer stands at the plunger and waits for the roster to clear. This is exactly the safety property the quarry wants: the detonation is coupled to the confirmations, so a step that has not completed can hold the whole operation. The responders run one after another in the same window of time, not off in some parallel world the shot-firer never hears from.
That same coupling is what makes a careless addition dangerous. Suppose someone decides the pre-blast roster should also "phone the regional authority to log the shot in real time," and wires that call directly into the synchronous confirmation sequence. Now every blast waits on an outside telephone line the quarry does not control. On the day that line is busy, the confirmation never comes back -- and because the sequence treats a missing confirmation as a fault, a blast that was otherwise ready to go is aborted. A slow, failure-prone, external task has been placed on the critical path of a fast local protocol. The fix is not to abandon the roster but to keep it to quick local confirmations, and to drop the authority notification into an out-tray for a runner to carry out after the blast, where its delays and failures cannot hold the plunger.
Syntax or Core Structure
A signal is a named broadcast. One piece of code -- the sender -- announces that something happened by calling send(). Any number of other pieces of code -- the receivers -- register interest ahead of time with connect(), and the framework calls each of them when the signal fires. The sender never references the receivers, and the receivers never reach into the sender; the signal object sits between them. Flask ships with a set of built-in signals -- backed by the blinker library, a hard dependency since Flask 2.3 -- that fire at key moments in the request lifecycle.
from flask import Flask, request_started, request
app = Flask(__name__)
log = []
def on_request_started(sender, **extra):
log.append(request.path)
request_started.connect(on_request_started, app)
@app.get("/hello")
def hello():
return "hi"
client = app.test_client()
client.get("/hello")
client.get("/hello?x=1")
print("receiver saw:", log)
print("count:", len(log))
Output:
receiver saw: ['/hello', '/hello']
count: 2
request_started is one of Flask's built-in signals. We connect our receiver with connect(receiver, app), passing the app as the sender so the receiver fires only for that application. Flask sends the signal for us on every request, after the request context is pushed -- which is why the request proxy is already available inside the receiver. The view function knows nothing about the receiver; adding or removing it changes what happens on each request without touching a single route. Note that request.path is /hello both times: the path never includes the query string, so the second request with ?x=1 records the same path.
Technical Depth: Custom Signals, Synchronous Dispatch, and Weak References
Defining and sending custom signals
You are not limited to Flask's built-in signals. Create your own with a blinker namespace, then send() from wherever the event happens.
from blinker import Namespace
my_signals = Namespace()
order_placed = my_signals.signal("order-placed")
received = []
def notify(sender, **kw):
received.append((sender, kw.get("order_id")))
return "notified"
order_placed.connect(notify)
results = order_placed.send("shop", order_id=42)
print("received:", received)
print("results:", [(r.__name__, v) for r, v in results])
Output:
received: [('shop', 42)]
results: [('notify', 'notified')]
Namespace().signal(name) returns a signal object, and calling .signal() again with the same name returns the same object -- so senders and receivers in different modules can find each other by name alone. send(sender, **kwargs) calls every connected receiver with that sender and those keyword arguments, and returns a list of (receiver, return_value) pairs. The return values are collected for your own use; Flask itself ignores them.
Dispatch is synchronous and in-process
Signals are not a message queue and not a thread pool. When you send(), every receiver runs immediately, in the current thread, before send() returns.
| Signal | Fires when | Receiver gets |
|---|---|---|
request_started | request context pushed, before the view | sender = app |
request_finished | after the view, before the response is sent | response |
request_tearing_down | request context is popped | exc or None |
template_rendered | just after a template renders | template, context |
got_request_exception | an unhandled exception occurs during a request | exception |
message_flashed | flash() is called | message, category |
from blinker import signal
pinged = signal("demo-ping")
order = []
def receiver(sender, **kw):
order.append("receiver ran")
raise ValueError("boom")
pinged.connect(receiver)
order.append("before send")
try:
pinged.send("x")
order.append("after send (not reached)")
except ValueError as exc:
order.append("caught: " + str(exc))
print(order)
Output:
['before send', 'receiver ran', 'caught: boom']
The list captures the exact order of events: receiver ran is recorded between before send and the except branch, proving the receiver executed inline. And because dispatch is synchronous, a receiver that raises is not swallowed -- the exception propagates straight out of send(), so after send (not reached) never runs. This is the single most important property of signals to internalize: a receiver's slowness is the sender's slowness, and a receiver's exception is the sender's exception.
Receivers, senders, and weak references
Two behaviors surprise people: how long a receiver lives, and which senders it hears.
| Concern | Behavior | What to do |
|---|---|---|
| Reference strength | connect() stores a weak reference by default | keep a module-level reference, or pass weak=False |
| Local functions and lambdas | garbage-collected, silently stop firing | avoid them, or connect with weak=False |
| Sender filtering | connect(fn, sender) fires only for that sender | scope a receiver to one app or blueprint |
| Return values | collected into a list by send() | use them yourself; Flask ignores them |
By default a signal holds a weak reference to each receiver, so if the only thing keeping a receiver alive is the connection itself -- a lambda, or a closure defined inside a function -- it is garbage-collected and stops firing with no error at all. The module-level functions used above are safe because their module keeps them alive; for anything else, pass weak=False or hold your own reference. The optional sender argument to connect() filters delivery: Flask sends its built-in signals with the app as sender, so connect(fn, app) scopes a receiver to one application, while connect(fn) receives from every sender of that signal.
Real World Example: An "Order Placed" Signal That Sends Email Inline
A tempting use of signals is to decouple side effects from the main path. An order-placement route saves the order and emits an order_placed signal; a receiver elsewhere sends the confirmation email, so the route never mentions email at all. It reads beautifully. Then the mail server goes down.
from flask import Flask, jsonify
from blinker import signal
app = Flask(__name__)
ORDERS = []
mail_log = []
OUTBOX = []
class MailProvider:
def __init__(self, working):
self.working = working
def send(self, to, body):
if not self.working:
raise RuntimeError("smtp timeout")
mail_log.append((to, body))
provider = MailProvider(working=False)
order_placed = signal("order-placed")
order_placed_safe = signal("order-placed-safe")
def send_confirmation(sender, order=None, **kw):
provider.send(order["email"], "Thanks for order " + str(order["id"]))
def enqueue_confirmation(sender, order=None, **kw):
OUTBOX.append(order["id"])
order_placed.connect(send_confirmation)
order_placed_safe.connect(enqueue_confirmation)
@app.post("/orders")
def create_order():
order = {"id": len(ORDERS) + 1, "email": "ada@x.io"}
ORDERS.append(order)
order_placed.send("shop", order=order)
return jsonify(order_id=order["id"]), 201
@app.post("/orders-fixed")
def create_order_fixed():
order = {"id": len(ORDERS) + 1, "email": "ada@x.io"}
ORDERS.append(order)
order_placed_safe.send("shop", order=order)
return jsonify(order_id=order["id"]), 201
client = app.test_client()
resp = client.post("/orders")
print("status:", resp.status_code)
print("orders saved:", len(ORDERS))
print("emails sent:", len(mail_log))
resp2 = client.post("/orders-fixed")
print("fixed status:", resp2.status_code)
print("outbox:", OUTBOX)
Output:
status: 500
orders saved: 1
emails sent: 0
fixed status: 201
outbox: [2]
The /orders route does the honest thing first: it saves the order, then emits the signal. The send_confirmation receiver, wired to order_placed, calls the mail provider synchronously; when the provider is down and raises, that exception propagates out of send() and out of the view, and Flask turns it into a 500. The output tells the whole story -- orders saved: 1 means the order really is in the system, yet the caller sees status: 500 and emails sent: 0.
From the customer's side this is simply a failed request, so they retry -- and because nothing stopped the first order from being saved, the retry creates a second one. A non-essential courtesy, the confirmation email, has not merely failed; it has corrupted the outcome of the essential action and manufactured a duplicate order. The blast was ready, and a busy phone line aborted it. The /orders-fixed route shows the discipline. Its receiver, enqueue_confirmation, does only fast local work -- it appends the order id to an outbox that a separate worker will drain later. Placing an order now returns 201 even with the mail server down, and the email is recorded as pending (outbox: [2]) instead of attempted inline. The signal still decouples the code -- the route still says nothing about email -- but the slow, failure-prone step has been moved off the request's critical path.
The genuine design flaw in the first version is doing slow, external, failure-prone work synchronously inside a signal receiver. Because send() is synchronous and propagates exceptions, a receiver runs on the caller's critical path with the caller's error budget: the request's latency now includes the SMTP round-trip, and the request's success now depends on the mail server being up. Signals are safe only for fast, local, best-effort notifications -- incrementing a metric, writing an audit line, busting a cache. Anything that touches the network or can fail belongs on a task queue (the subject of the background-jobs lesson), and even a lightweight receiver should guard itself so it never raises into its sender. Decoupling the code is not the same as decoupling the execution: a signal does the first, never the second.
Common Mistakes
- Assuming signals are asynchronous.
send()is a synchronous, in-process function call, not a queue. Every receiver runs beforesend()returns, on the same thread, inside the same request.
- Doing slow or external work in a receiver. Sending email, calling a third-party API, or writing to a slow store inside a receiver puts that latency and that failure risk directly on the request's critical path.
- Letting a receiver raise into its sender. An unhandled exception in a receiver propagates out of
send(). For best-effort work, wrap the body intry/exceptand log the failure rather than letting it break the caller.
- Connecting a lambda or a local function. Signals hold weak references by default, so a receiver with no other reference is garbage-collected and silently stops firing. Use a module-level function or pass
weak=False.
- Forgetting the
**extracatch-all in the receiver signature. Signals may send keyword arguments you did not anticipate, and Flask's built-ins send several. A receiver that does not accept**extrabreaks the moment the payload grows. Always end the signature with**extra.
- Filtering by a sender you never actually send. If you
connect(fn, some_sender)but latersend()with a different sender (or none at all), the receiver never fires -- and you get silence, not an error, which is far harder to debug.
- Depending on receiver execution order. blinker does not guarantee the order in which receivers run. If two steps must happen in sequence, that is a pipeline, not two independent subscribers -- write it as explicit calls.
- Branching on a receiver's return value.
send()collects return values, but you cannot assume any particular receiver is even connected. Do not build required control flow on what a receiver returns.
- Reaching for a signal when a direct call is clearer. If exactly one place needs to react and the coupling is harmless, call the function directly. A signal adds indirection that only pays off when senders and receivers genuinely should not know about each other.
Best Practices
- Keep receivers fast, local, and best-effort. A good receiver increments a counter, writes a log line, or invalidates a cache entry -- work that finishes in microseconds and cannot fail in a way that matters to the request.
- Offload anything slow or external to a task queue. If the reaction sends email, calls an API, or writes across the network, have the receiver enqueue a job and return immediately, and let a worker do the slow part.
- Accept
**extrain every receiver. Future-proof the signature so a new payload key never breaks an existing receiver.
- Guard best-effort receivers so they cannot raise into the sender. Wrap the body in
try/except, log the error, and return; a broken notification should never break the action that triggered it.
- Connect module-level functions, or pass
weak=False. Make sure something other than the connection itself keeps the receiver alive, so it does not vanish to the garbage collector.
- Scope receivers with a sender when it matters. Pass the app or blueprint as the sender filter so a receiver only fires for the application you intend -- especially when tests create multiple apps.
- Prefer a plain function call for one-to-one coupling. Use signals for genuine fan-out to independent, optional subscribers, not as a fashionable substitute for calling a function.
- Document each custom signal. Record its name, who sends it, and the exact payload keys, so receivers in other modules can rely on a stable contract.
Practice Exercises
- Log every request with a signal. Connect a receiver to
request_finished, read theresponseargument, and recordrequest.method,request.path, andresponse.status_code. Drive two requests throughapp.test_client()and assert your log has the expected entries -- without adding anything to the view functions.
- A custom event with two independent subscribers. Define a
user_registeredsignal. Connect one receiver that appends to an audit list and another that appends the new user's id to a welcome-email outbox.send()the signal once and assert both reacted, demonstrating fan-out to receivers that do not know about each other.
- Turn a request-breaking receiver into a best-effort one. Reproduce the inline-email
500from the Real World example, then rewritesend_confirmationto catch its ownRuntimeError, log it, and return. Show that placing an order now yieldsstatus: 201withemails sent: 0, so the failure no longer corrupts the order.
- Demonstrate the weak-reference trap. Connect a receiver defined inside a function (a closure), call
gc.collect(), and show thatsend()no longer reaches it. Then fix it by connecting the same logic withweak=Falseand show the receiver fires again.